JavaScript函数调用 了解了从JavaScript环境中获取不同值以及调用函数的方法,那么反过来,如何在JavaScript环境中获取Objective-C或者Swift定义的自定义对象和方法呢?要从JSContext中获取本地客户端代码,主要有两种途径,分别为Blocks和JSExport协议。 在JSContext中,如果Objective-C代码块赋值为一个标识符,JavaScriptCore就会自动将其封装在JavaScript函数中,因而在JavaScript上使用Foundation和Cocoa类就更方便些——这再次验证了JavaScriptCore强大的衔接作用。现在CFStringTransform也能在JavaScript上使用了,如下所示: -
- context[@"simplifyString"] = ^(NSString *input) {
- NSMutableString *mutableString = [input mutableCopy];
- CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO);
- CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformStripCombiningMarks, NO);
- return mutableString;
- };
- NSLog(@"%@", [context evaluateScript:@"simplifyString('안녕하새요!')"]);
-
- let simplifyString: @objc_block String -> String = { input in
- var mutableString = NSMutableString(string: input) as CFMutableStringRef
- CFStringTransform(mutableString, nil, kCFStringTransformToLatin, Boolean(0))
- CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0))
- return mutableString
- }
- context.setObject(unsafeBitCast(simplifyString, AnyObject.self), forKeyedSubscript: "simplifyString")
-
- println(context.evaluateScript("simplifyString('안녕하새요!')"))
-
需要注意的是,Swift的speedbump只适用于Objective-C block,对Swift闭包无用。要在一个JSContext里使用闭包,有两个步骤:一是用@objc_block来声明,二是将Swift的knuckle-whitening unsafeBitCast()函数转换为 AnyObject。
代码块可以捕获变量引用,而JSContext所有变量的强引用都保留在JSContext中,所以要注意避免循环强引用问题。另外,也不要在代码块中捕获JSContext或任何JSValues,建议使用[JSContext currentContext]来获取当前的Context对象,根据具体需求将值当做参数传入block中。
借助JSExport协议也可以在JavaScript上使用自定义对象。在JSExport协议中声明的实例方法、类方法,不论属性,都能自动与JavaScrip交互。文章稍后将介绍具体的实践过程。
JavaScriptCore实践 我们可以通过一些例子更好地了解上述技巧的使用方法。先定义一个遵循JSExport子协议PersonJSExport的Person model,再用JavaScript在JSON中创建和填入实例。有整个JVM,还要NSJSONSerialization干什么?
Person类执行的PersonJSExports协议具体规定了可用的JavaScript属性。,在创建时,类方法必不可少,因为JavaScriptCore并不适用于初始化转换,我们不能像对待原生的JavaScript类型那样使用var person = new Person()。 -
-
- @class Person;
- @protocol PersonJSExports <JSExport>
- @property (nonatomic, copy) NSString *firstName;
- @property (nonatomic, copy) NSString *lastName;
- @property NSInteger ageToday;
- - (NSString *)getFullName;
-
- + (instancetype)createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
- @end
- @interface Person : NSObject <PersonJSExports>
- @property (nonatomic, copy) NSString *firstName;
- @property (nonatomic, copy) NSString *lastName;
- @property NSInteger ageToday;
- @end
-
- @implementation Person
- - (NSString *)getFullName {
- return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
- }
- + (instancetype) createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
- Person *person = [[Person alloc] init];
- person.firstName = firstName;
- person.lastName = lastName;
- return person;
- }
- @end
-
-
- @objc protocol PersonJSExports : JSExport {
- var firstName: String { get set }
- var lastName: String { get set }
- var birthYear: NSNumber? { get set }
- func getFullName() -> String
-
- class func createWithFirstName(firstName: String, lastName: String) -> Person
- }
-
- @objc class Person : NSObject, PersonJSExports {
-
- dynamic var firstName: String
- dynamic var lastName: String
- dynamic var birthYear: NSNumber?
- init(firstName: String, lastName: String) {
- self.firstName = firstName
- self.lastName = lastName
- }
- class func createWithFirstName(firstName: String, lastName: String) -> Person {
- return Person(firstName: firstName, lastName: lastName)
- }
- func getFullName() -> String {
- return "\(firstName) \(lastName)"
- }
- }
创建Person类之后,需要先将其导出到JavaScript环境中去,同时还需导入Mustache JS库,以便对Person对象应用模板。 -
-
- context[@"Person"] = [Person class];
-
- NSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
- [context evaluateScript:mustacheJSString];
-
-
- context.setObject(Person.self, forKeyedSubscript: "Person")
-
- if let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) {
- context.evaluateScript(mustacheJSString)
- }
以下简单列出一个JSON范例,以及用JSON来创建新Person实例。 注意:JavaScriptCore实现了Objective-C/Swift的方法名和JavaScript代码交互。因为JavaScript没有命名好的参数,任何额外的参数名称都采取驼峰命名法(Camel-Case),并附加到函数名称上。在此示例中,Objective-C的方法createWithFirstName:lastName:在JavaScript中则变成了createWithFirstNameLastName()。 -
- [
- { "first": "Grace", "last": "Hopper", "year": 1906 },
- { "first": "Ada", "last": "Lovelace", "year": 1815 },
- { "first": "Margaret", "last": "Hamilton", "year": 1936 }
- ]
-
- var loadPeopleFromJSON = function(jsonString) {
- var data = JSON.parse(jsonString);
- var people = [];
- for (i = 0; i < data.length; i++) {
- var person = Person.createWithFirstNameLastName(data[i].first, data[i].last);
- person.birthYear = data[i].year;
- people.push(person);
- }
- return people;
- }
现在你只需加载JSON数据,并在JSContext中调用,将其解析到Person对象数组中,再用Mustache模板渲染即可: -
-
- NSString *peopleJSON = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
-
- JSValue *load = context[@"loadPeopleFromJSON"];
-
- JSValue *loadResult = [load callWithArguments:@[peopleJSON]];
- NSArray *people = [loadResult toArray];
-
- JSValue *mustacheRender = context[@"Mustache"][@"render"];
- NSString *template = @"{{getFullName}}, born {{birthYear}}";
-
- for (Person *person in people) {
- NSLog(@"%@", [mustacheRender callWithArguments:@[template, person]]);
- }
-
-
-
-
-
-
- if let peopleJSON = NSString(contentsOfFile:..., encoding: NSUTF8StringEncoding, error: nil) {
-
- let load = context.objectForKeyedSubscript("loadPeopleFromJSON")
-
- if let people = load.callWithArguments([peopleJSON]).toArray() as? [Person] {
-
-
- let mustacheRender = context.objectForKeyedSubscript("Mustache").objectForKeyedSubscript("render")
- let template = "{{getFullName}}, born {{birthYear}}"
-
-
- for person in people {
- println(mustacheRender.callWithArguments([template, person]))
- }
- }
- }
-
-
-
-
(编译/张新慧) 文章来源:NSHipster |