关于 RubyMotion 我已经写过很多文章了,但如何混用Objective-C与Ruby还从未涉及到。实际上你能在RubyMotion项目中使用Objective-C代码,也可以在传统Objective-C的App中使用Ruby代码。也许你一次听来觉得像黑魔法一样,所以来一起看看下面这些示例。
Objective-C in Ruby
很多iOS开发者在现有的Objecive-C代码中存在大量深层的备份日志,这样就为项目手动转换为 RubyMotion 带来了很大的痛苦。然而幸运的是现在仅仅只需要将编译好的Objective-C代码添加到我们的新RubyMotion应用里。
比如我们要在 RubyMotion 应用中使用 Objective-C 形式的 CYAlert 类:
// 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
那么现在在 AppDelegate 中,我们这样使用 CYAlert:
class AppDelegate def application(application, didFinishLaunchingWithOptions:launchOptions) CYAlert.show true end end
非常简单,不是吗?关于RubyMotion是如何做到这一点的,你可以从RubyMotion docs.查阅更多信息。
CocoaPods
因为RubyMotion能够创建旧式 Xcode 项目,所以使用CocoaPods系统是不需要大量的图示解说的。
require 'motion-cocoapods' Motion::Project::App.setup do |app| # ... app.pods do pod 'JSONKit' end end
Ruby in Objective-C
这里我们有两种方法编译成普通字节码:直接将Ruby的类打包后再Objective-C项目中使用,感觉不可思议?OK,假设我们有一个CYAlert类,Ruby形式。如下代码演示:
# ./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项目中使用它:
1,项目中添加静态库

2,然后添加下图的几个库

3,初始化 RubyMotion 运行时
// main.m int main(int argc, char *argv[]) { @autoreleasepool { void RubyMotionInit(int, char **); RubyMotionInit(argc, argv); ... } }
那么剩下的都是小菜一碟,不过有个警告:RubyMotion不会为项目生成 .h 文件,所以需要使用Objective-C手动定义这些类与它的方法。所以手动写一个 CYAlert.h :
// 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。
好了,这里放出Github上源码下载。
引用来自“fants”的答案