翻译于 2012/11/27 11:25
// CYAlert.h #import <UIKit/UIKit.h>@interface CYAlert : NSObject + (void)show;@end // CYAlert.m #import "CYAlert.h" @implementation CYAlert + (void)show { UIAlertView *alert = [[UIAlertView alloc] init]; alert.title = @"This is Objective-C"; alert.message = @"Mixing and matching!"; [alert addButtonWithTitle:@"OK"]; [alert show]; [alert release]; }@end
为了在RubyMotion应用中能正常使用,这里需要将CYAlert的两个文件都放置到类似 ./vendor/CYAlert 里面,然后在 Rakefile: 中告诉 RubyMotion 使用vendor_project创建那个文件夹。
Motion::Project::App.setup do |app| # Use `rake config' to see complete project settings. app.name = 'MixingExample' # ./vendor/CYAlert contains CYAlert.h and CYAlert.m app.vendor_project('vendor/CYAlert', :static) end
class AppDelegate def application(application, didFinishLaunchingWithOptions:launchOptions) CYAlert.show true end end
require 'motion-cocoapods' Motion::Project::App.setup do |app| # ... app.pods do pod 'JSONKit' end end
Ruby in Objective-C
# ./app/CYAlert.rb class CYAlert def self.show alert = UIAlertView.alloc.init alert.title = "This is Ruby" alert.message = "Mixing and matching!" alert.addButtonWithTitle "OK" alert.show end end
如果运行 rake static,将会把项目编译成静态库 ./build/<app name>-universal.a。下面我们通过几个步骤看看如何在Xcode项目中使用它:
// main.m int main(int argc, char *argv[]) { @autoreleasepool { void RubyMotionInit(int, char **); RubyMotionInit(argc, argv); ... } }
// CYAlert.h@interface CYAlert : NSObject + (void)show;@end @implementation CYAlert // Empty on purpose@end
// ExampleDelegate.m #import "CYAlert.h" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... [CYAlert show]; return YES; }
所以,如果你觉得写Objective-C代码很痛苦的话(译者:觉得它比任何其他语言都痛苦),完全可以使用Ruby来写相同的功能,最后转换一下就OK。
评论删除后,数据将无法恢复
评论(0)