本文作者Nate Cook是一位独立的Web及移动应用开发者,是继Mattt大神之后NSHipster的主要维护者,也是非常知名活跃的Swift博主,并且还是支持自动生成Swift在线文档的SwiftDoc.org网站创造者。在本文中,他介绍了在Swift中使用
在RedMonk发布的2015年1月编程语言排行榜中,Swift采纳率排名迅速飙升,从刚刚面世时的68位跃至22位,Objective-C仍然稳居TOP10,而
而早在2013年苹果发布的OS X Mavericks和iOS 7两大系统中便均已加入了
X和iOS系统等高速虚拟机也蓬勃发展起来。
JSContext/JSValue
JSContext即
- //Objective-C
- JSContext *context = [[JSContext alloc] init];
- [context evaluate
Script :@"var num = 5 + 5"];- [context evaluate
Script :@"var names = ['Grace', 'Ada', 'Margaret']"];- [context evaluate
Script :@"var triple = function(value) { return value * 3 }"];- JSValue *tripleNum = [context evaluate
Script :@"triple(num)"];
- //Swift
- let context = JSContext()
- context.evaluate
Script ("var num = 5 + 5")- context.evaluate
Script ("var names = ['Grace', 'Ada', 'Margaret']")- context.evaluate
Script ("var triple = function(value) { return value * 3 }")- let tripleNum: JSValue = context.evaluate
Script ("triple(num)")
像
JSValue包含了一系列用于获取Underlying Value的方法,如下表所示:
想要检索上述示例中的tripleNum值,只需使用相应的方法即可:
- //Objective-C
- NSLog(@"Tripled: %d", [tripleNum toInt32]);
- // Tripled: 30
- //Swift
- println("Tripled: \(tripleNum.toInt32())")
- // Tripled: 30
下标值(Sub
通过在JSContext和JSValue实例中使用下标符号可以轻松获取上下文环境中已存在的值。其中,JSContext放入对象和数组的只能是字符串下标,而JSValue则可以是字符串或整数下标。
- //Objective-C
- JSValue *names = context[@"names"];
- JSValue *initialName = names[0];
- NSLog(@"The first name: %@", [initialName toString]);
- // The first name: Grace
- //Swift
- let names = context.objectForKeyedSub
script ("names")- let initialName = names.objectAtIndexedSub
script (0)- println("The first name: \(initialName.toString())")
- // The first name: Grace
而Swift语言毕竟才诞生不久,所以并不能像Objective-C那样自如地运用下标符号,目前,Swift的方法仅能实现objectAtKeyedSub
函数调用(Calling Functions)
我们可以将Foundation类作为参数,从Objective-C/Swift代码上直接调用封装在JSValue的
- //Objective-C
- JSValue *tripleFunction = context[@"triple"];
- JSValue *result = [tripleFunction callWithArguments:@[@5] ];
- NSLog(@"Five tripled: %d", [result toInt32]);
- //Swift
- let tripleFunction = context.objectForKeyedSub
script ("triple")- let result = tripleFunction.callWithArguments([5])
- println("Five tripled: \(result.toInt32())")
异常处理(Exception Handling)
JSContext还有一个独门绝技,就是通过设定上下文环境中exceptionHandler的属性,可以检查和记录语法、类型以及出现的运行时错误。exceptionHandler是一个回调处理程序,主要接收JSContext的reference,进行异常情况处理。
- //Objective-C
- context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
- NSLog(@"JS Error: %@", exception);
- };
- [context evaluate
Script :@"function multiply(value1, value2) { return value1 * value2 "];- // JS Error: SyntaxError: Unexpected end of
script
- //Swift
- context.exceptionHandler = { context, exception in
- println("JS Error: \(exception)")
- }
- context.evaluate
Script ("function multiply(value1, value2) { return value1 * value2 ")- // JS Error: SyntaxError: Unexpected end of
script
了解了从
Blocks (块)
在JSContext中,如果Objective-C代码块赋值为一个标识符,
- //Objective-C
- 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 evaluate
Script :@"simplifyString('?????!')"]);
- //Swift
- 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), forKeyedSub
script : "simplifyString")- println(context.evaluate
Script ("simplifyString('?????!')"))- // annyeonghasaeyo!
需要注意的是,Swift的speedbump只适用于Objective-C block,对Swift闭包无用。要在一个JSContext里使用闭包,有两个步骤:一是用@objc_block来声明,二是将Swift的knuckle-whitening unsafeBitCast()函数转换为 AnyObject。
内存管理(Memory Management)
代码块可以捕获变量引用,而JSContext所有变量的强引用都保留在JSContext中,所以要注意避免循环强引用问题。另外,也不要在代码块中捕获JSContext或任何JSValues,建议使用[JSContext currentContext]来获取当前的Context对象,根据具体需求将值当做参数传入block中。
JSExport协议
借助JSExport协议也可以在
我们可以通过一些例子更好地了解上述技巧的使用方法。先定义一个遵循JSExport子协议PersonJSExport的Person model,再用
PersonJSExports和Person
Person类执行的PersonJSExports协议具体规定了可用的
- //Objective-C
- // in Person.h -----------------
- @class Person;
- @protocol PersonJSExports @property (nonatomic, copy) NSString *firstName;
- @property (nonatomic, copy) NSString *lastName;
- @property NSInteger ageToday;
- - (NSString *)getFullName;
- // create and return a new Person instance with `firstName` and `lastName`
- + (instancetype)createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
- @end
- @interface Person : NSObject @property (nonatomic, copy) NSString *firstName;
- @property (nonatomic, copy) NSString *lastName;
- @property NSInteger ageToday;
- @end
- // in Person.m -----------------
- @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
- //Swift
- // Custom protocol must be declared with `@objc`
- @objc protocol PersonJSExports : JSExport {
- var firstName: String { get set }
- var lastName: String { get set }
- var birthYear: NSNumber? { get set }
- func getFullName() -> String
- /// create and return a new Person instance with `firstName` and `lastName`
- class func createWithFirstName(firstName: String, lastName: String) -> Person
- }
- // Custom class must inherit from `NSObject`
- @objc class Person : NSObject, PersonJSExports {
- // properties must be declared as `dynamic`
- 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)"
- }
- }
配置JSContext
创建Person类之后,需要先将其导出到
- //Objective-C
- // export Person class
- context[@"Person"] = [Person class];
- // load Mustache.js
- NSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
- [context evaluate
Script :mustacheJSString];
- //Swift
- // export Person class
- context.setObject(Person.self, forKeyedSub
script : "Person")- // load Mustache.js
- if let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) {
- context.evaluate
Script (mustacheJSString)- }
以下简单列出一个JSON范例,以及用JSON来创建新Person实例。
注意:
- //JSON
- [
- { "first": "Grace", "last": "Hopper", "year": 1906 },
- { "first": "Ada", "last": "Lovelace", "year": 1815 },
- { "first": "Margaret", "last": "Hamilton", "year": 1936 }
- ]
- //
JavaScript - 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模板渲染即可:
- //Objective-C
- // get JSON string
- NSString *peopleJSON = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
- // get load function
- JSValue *load = context[@"loadPeopleFromJSON"];
- // call with JSON and convert to an NSArray
- JSValue *loadResult = [load callWithArguments:@[peopleJSON]];
- NSArray *people = [loadResult toArray];
- // get rendering function and create template
- JSValue *mustacheRender = context[@"Mustache"][@"render"];
- NSString *template = @"{{getFullName}}, born {{birthYear}}";
- // loop through people and render Person object as string
- for (Person *person in people) {
- NSLog(@"%@", [mustacheRender callWithArguments:@[template, person]]);
- }
- // Output:
- // Grace Hopper, born 1906
- // Ada Lovelace, born 1815
- // Margaret Hamilton, born 1936
- //Swift
- // get JSON string
- if let peopleJSON = NSString(contentsOfFile:..., encoding: NSUTF8StringEncoding, error: nil) {
- // get load function
- let load = context.objectForKeyedSub
script ("loadPeopleFromJSON")- // call with JSON and convert to an array of `Person`
- if let people = load.callWithArguments([peopleJSON]).toArray() as? [Person] {
- // get rendering function and create template
- let mustacheRender = context.objectForKeyedSub
script ("Mustache").objectForKeyedSubscript ("render")- let template = "{{getFullName}}, born {{birthYear}}"
- // loop through people and render Person object as string
- for person in people {
- println(mustacheRender.callWithArguments([template, person]))
- }
- }
- }
- // Output:
- // Grace Hopper, born 1906
- // Ada Lovelace, born 1815
- // Margaret Hamilton, born 1936