iOS7 JavaStriptCore

IOS7开发~JavaScriptCore(一)

http://blog.csdn.net/zfpp25_/article/details/9232129

IOS7开发~JavaScriptCore(二)

http://blog.csdn.net/zfpp25_/article/details/9236357



IOS7之前,接触 JS 更多的是处理UIWebView的时候,如:http://blog.csdn.net/zfpp25_/article/details/8650412

但IOS7引入了JS框架<JavaScriptCore/JavaScriptCore.h>,给了“纯IOS程序员”一个枯木逢春的契机~学习强大的 JavaScript。



1、 基本概念


JavaScriptCore.framework :iOS7 中新加入的框架,用来处理JavaScript。JavaScriptCore 是苹果 Safari 浏览器的 JavaScript 引擎,JavaScriptCor在 OS X 平台上很早就存在的,而在 iOS 平台,直到IOS7才对外开放,并提供了 Objective-C 的接口


2、主要内容

Objective-C → JavaScript
• JavaScript → Objective-C 

• Memory management
• Threading
• JavaScriptCore C API
• JavaScriptCore with a WebView


首先引入框架   #import <JavaScriptCore/JavaScriptCore.h>


一、Objective-C → JavaScript

了解下面几个类:

JSContext:An instance of JSContext represents a JavaScript execution environment.(一个 Context 就是一个 JavaScript 代码执行的环境,也叫作用域。

JSValue:Conversion between Objective-C and JavaScript types.(JS是弱类型的,ObjectiveC是强类型的,JSValue被引入处理这种类型差异,在 Objective-C 对象和 JavaScript 对象之间起转换作用

Objective-C 和 JavaScript 中类型的对照表:



实例代码:1

  1. int main() {  
  2.     JSContext *context = [[JSContextalloc]init];  
  3.     JSValue *result = [context evaluateScript:@"2 + 2"];  
  4.     NSLog(@"2 + 2 = %d", [result toInt32]);  
  5.     return 0;  
  6. }  

实例代码:2

(1)新建一个test.js文件,其中实现代码:

  1. //计算阶乘  
  2. var factorial = function(n) {  
  3.     if (n < 0)  
  4.         return;  
  5.     if (n === 0)  
  6.         return 1;  
  7.     return n * factorial(n - 1)  
  8. };  



(2)调用时实现代码:

  1. - (void) factorial  
  2.     {  
  3.         NSString *path = [[NSBundlemainBundle]pathForResource:@"test"ofType:@"js"];  
  4.         NSString *testScript = [NSStringstringWithContentsOfFile:pathencoding:NSUTF8StringEncodingerror:nil];  
  5.           
  6.         JSContext *context = [[JSContextalloc]init];  
  7.         [context evaluateScript:testScript];  
  8.           
  9.         JSValue *function = context[@"factorial"];  
  10.         JSValue *result = [function callWithArguments:@[@10]];  
  11.         NSLog(@"factorial(10) = %d", [resulttoInt32]);  
  12.     }  

这样就计算出了10的阶乘。


注意:如果运行结果不正确,注意js文件是否已经加到项目的Buddle Resources中




二、JavaScript → Objective-C


• Two ways to interact with Objective-C from JavaScript (可以通过两种方式在 JavaScript 中调用 Objective-C

Blocks :JS functions (对应 JS 函数
JSExport protocol :JS objects (对应 JS 对象


(1)Blocks

  1. - (void) testMakeUIColor  
  2.     {  
  3.         JSContext *context = [[JSContextalloc]init];  
  4.           
  5.         context[@"creatUIColor"] = ^(NSDictionary *rgbColor){  
  6.             return [UIColor colorWithRed:([rgbColor[@"red"] floatValue] /255.0)  
  7.                                    green:([rgbColor[@"green"]floatValue] /255.0)  
  8.                                     blue:([rgbColor[@"blue"]floatValue] /255.0)  
  9.                                    alpha:1];  
  10.         };  
  11.         JSValue *color = [contextevaluateScript:@"makeUIColor({red: 150, green: 150, blue: 200})"];  
  12.         NSLog(@"color:%@",[colortoObject]);  
  13.     }  

注意:

1、Avoid capturing JSValues,  Prefer passing as arguments.(不要在 Block 中直接使用外面的 JSValue 对象, 把 JSValue 当做参数来传进 Block 中。)

2、Avoid capturing JSContexts, Use + [JSContext currentContext] (避免循引用,不要在 Block 中直接引用使用外面的 JSContext 对象,应该用[JSContext currentContext];)

错误的做法:



正确的做法:



(2)JSExport protocol

首先引入 

#import <objc/runtime.h>

实例代码1:    JS代码设置Button 的 title

  1. @protocol UIButtonExport <JSExport>  
  2. - (void)setTitle:(NSString *)title forState:(UIControlState)state;  
  3. @end  
  4. - (void) test  
  5. {  
  6.     class_addProtocol([UIButtonclass],@protocol(UIButtonExport));  
  7.       
  8. UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];  
  9.     [button setTitle:@"Hello Objective-C"forState:UIControlStateNormal];  
  10.     button.frame = CGRectMake(20,40,280,40);  
  11.   
  12.     JSContext *context = [[JSContextalloc]init];  
  13. context[@"button"] = button;  
  14. [context evaluateScript:@"button.setTitleForState('Hello JavaScript', 0)"];  
  15.       
  16.     [self.view addSubview:button];  
  17. }  


说明:

上面代码中,我们申明一个 UIButtonExport 协议,该协议继承于 JSExport,并将setTitle:forState:方法开放到该协议中(只有 JSExport 协议中的方法才能被 JavaScript 识别),然后通过运行时让 UIButton 遵循 UIButtonExport 协议。这样你就可以在 JS 中为 Button 设置 title 了,需要说明一点的是,在 JS 中方法的命名规则与 Objective-C 中有点不一样,如 Objective-C 中的方法-(void)setX:(id)x Y:(id)y Z:(id)z;,加入到 JSExport 协议中,在 JS 中调用就得是setXYZ(x, y, z);,当然如果你不想根据这种命名转换规则,你也可以通过 JSExport.h 中的方法来修改:


#define JSExportAs(PropertyName, Selector) \
    @optional Selector __JS_EXPORT_AS__##PropertyName:(id)argument; @required Selector
#endif

如 setX:Y:Z 方法,我们可以给他重命名,让 JS 中通过 set3D(x,y,z) 来调用

JSExportAs(set3D,
     - (void)setX:(id)x Y:(id)y Z:(id)z
);

实例代码2:

a、新建类 NativeObject,代码实现L:

.h代码:

  1. #import <Foundation/Foundation.h>  
  2. @import JavaScriptCore;  
  3. @protocol NativeObjectExport <JSExport>  
  4. -(void)log:(NSString*)string;  
  5. @end  
  6.   
  7. @interface NativeObject : NSObject <NativeObjectExport>  
  8. @end  
  9.   
  10. .m代码:  
  11. #import "NativeObject.h"  
  12. @implementation NativeObject  
  13.   
  14. -(void)log:(NSString*)string {  
  15.     NSLog(@"js: %@", string);  
  16. }  
  17. @end  
  18.   
  19. 调用代码:  
  20. - (void) testLog  
  21. {  
  22.     JSContext *context = [[JSContextalloc]init];  
  23.     context[@"nativeObject"] = [[NativeObjectalloc]init];  
  24.     [context evaluateScript:@"nativeObject.log(\"Hello Javascript\")"];  
  25. }  


三、Memory management

1• Objective-C uses ARC(OC 使用ARC机制
2• JavaScriptCore uses garbage collection (JS 使用垃圾回收机制
              ■ All references are strong (JS中全部都是“强引用”
3• API memory management is mostly automatic 

4• Two situations that require extra attention: (几乎SDK已经做好了很多事情,所以开发者只需要重点掌握以下亮点
              ■ Storing JavaScript values in Objective-C objects 

              ■ Adding JavaScript fields to Objective-C objects

(英文文档只要被翻译了,就难免失去原有的含义,尽量不翻译~)


根据官方文档关于JS-OC内存管理总结:由于JS中全部都是强引用,如果JS 与 OC互相引用时,就要防止OC也强引用JS,这样会形成引用循环,所以OC要想办法弱引用,但弱引用会被系统释放,所以把可能被释放的对象放到一个容器中来防止对象被被错误释放。

看代码(一):

JS:

function ClickHandler(button, callback) {
     this.button = button;
     this.button.onClickHandler = this;
     this.handleEvent = callback;
};

OC:

@implementation MyButton
- (void)setOnClickHandler:(JSValue *)handler
{
     _onClickHandler = handler; // Retain cycle
}
@end


如果直接保存 handler,就会出现内存泄露,因为 JS 中引用 button 对象是强引用,如果 Button 也用强引用来保存 JS 中的 handler,这就导致了 循环引用。我们没法改变 JavaScript 中的强引用机制,只能在 Objective-C 中弱引用 handler,为了防止 onclick handler 被错误释放, JavaScriptCore 给出的解决方案如下:

- (void)setOnClickHandler:(JSValue *)handler
{
     _onClickHandler = [JSManagedValue managedValueWithValue:handler];
     [_context.virtualMachine addManagedReference:_onClickHandler
                                        withOwner:self]
}

代码(二):

- (void)loadColorsPlugin

{    

    // Load the plugin script from the bundle.

    NSString *path = [[NSBundlemainBundle]pathForResource:@"colors"ofType:@"js"];

    NSString *pluginScript = [NSStringstringWithContentsOfFile:pathencoding:NSUTF8StringEncodingerror:nil];

    

    _context = [[JSContextalloc]init];

    

    // We insert the AppDelegate into the global object so that when we call

    // -addManagedReference:withOwner: for the plugin object we're about to load

    // and pass the AppDelegate as the owner, the AppDelegate itself is reachable from

    // within JavaScript. If we didn't do this, the AppDelegate wouldn't be reachable

    // from JavaScript, and there wouldn't be anything keeping the plugin object alive.

    _context[@"AppDelegate"] =self;

    

    // Insert a block so that the plugin can create NSColors to return to us later.

    _context[@"makeNSColor"] = ^(NSDictionary *rgb){

        return [NSColorcolorWithRed:[rgb[@"red"]floatValue] / 255.0f

                               green:[rgb[@"green"]floatValue] /255.0f

                                blue:[rgb[@"blue"]floatValue] /255.0f

                               alpha:1.0f];

    };

    

    JSValue *plugin = [_contextevaluateScript:pluginScript];

    

    _colorPlugin = [JSManagedValuemanagedValueWithValue:plugin];

    [_context.virtualMachineaddManagedReference:_colorPluginwithOwner:self];

    [self.windowsetDelegate:self];

}



注意:

JSManagedValue:

 The primary use case for JSManagedValue is for safely referencing JSValues 

 from the Objective-C heap. It is incorrect to store a JSValue into an 

 Objective-C heap object, as this can very easily create a reference cycle, 

keeping the entire JSContext alive. 

将 JSValue 转为 JSManagedValue 类型后,可以添加到 JSVirtualMachine 对象中,这样能够保证你在使用过程中 JSValue 对象不会被释放掉,当你不再需要该 JSValue 对象后,从 JSVirtualMachine 中移除该 JSManagedValue 对象,JSValue 对象就会被释放并置空。


JSVirtualMachine:

All instances of JSContext are associated with a single JSVirtualMachine. The 

virtual machine provides an "object space" or set of execution resources.(JSVirtualMachine就是一个用于保存弱引用对象的数组,加入该数组的弱引用对象因为会被该数组 retain,所以保证了使用时不会被释放,当数组里的对象不再需要时,就从数组中移除,没有了引用的对象就会被系统释放。


四、Threading

• API is thread safe
• Locking granularity is JSVirtualMachine

          ■ Use separate JSVirtualMachines for concurrency/parallelism


五、JavaScriptCore C API

JSValue ↔ JSValueRef :

        JSValueRef valueRef = XXX;
       JSValue *value = [JSValue valueWithJSValueRef:valueRef inContext:context];


       JSValue *value =  XXX;
      JSValueRef valueRef = [value JSValueRef];


JSContext ↔ JSGlobalContextRef :

        JSGlobalContextRef ctx =  XXX;
        JSContext *context = [JSContext contextWithJSGlobalContextRef:ctx];


        JSContext *context =  XXX;
        JSGlobalContextRef ctx = [context JSGlobalContextRef];


五、JavaScriptCore with a WebView (Mac)

暂不讨论,Demos下载中有项目源码。


参考资料:

https://developer.apple.com/library/mac/#documentation/Carbon/Reference/ WebKit_JavaScriptCore_Ref/

https://developer.apple.com/wwdc/schedule/details.php?id=615

https://github.com/zynga/jsbindings

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/WebKit/Protocols/WebScripting_Protocol/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/WebKit/Classes/WebScriptObject_Class/Reference/Reference.html#//apple_ref/doc/c_ref/WebScriptObject


Demos下载直通车:http://pan.baidu.com/s/14AIAq(其中 TestJS 项目为本文测试使用项目)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值