本文作者 Nate Cook 是一位獨立的 Web 與行動應用開發者,也是繼 Mattt 之後 NSHipster 的主要維護者、知名活躍的 Swift 博主,同時是支持自動生成 Swift 線上文檔的 SwiftDoc.org 網站創建者。以下為譯文。
在 RedMonk 發布的 2015 年 1 月程式語言排行榜中,Swift 的採用率迅速飆升,從剛面世時的第 68 位一躍至第 22 位;Objective-C 仍穩居前十,而 JavaScript 則憑藉其在 iOS 平台上的原生體驗優勢,成為年度最火熱的語言。

其實早在 2013 年 Apple 發布的 OS X Mavericks 與 iOS 7 中,就已加入 JavaScriptCore 框架,讓開發者能輕鬆、快捷、安全地用 JavaScript 撰寫應用。無論評價褒貶,JavaScript 的霸主地位已成定局,相關工具與資源層出不窮。
JSContext 是 JavaScript 代碼的運行環境,也就是一個作用域。當你在瀏覽器中運行 JavaScript 時,JSContext 就相當於一個窗口,能執行建立變量、運算乃至定義函數等操作:
//Objective-C JSContext *context = [[JSContext alloc] init]; [context evaluateScript:@"var num = 5 + 5"]; [context evaluateScript:@"var names = ['Grace', 'Ada', 'Margaret']"]; [context evaluateScript:@"var triple = function(value) { return value * 3 }"]; JSValue *tripleNum = [context evaluateScript:@"triple(num)"];//Swift let context = JSContext() context.evaluateScript("var num = 5 + 5") context.evaluateScript("var names = ['Grace', 'Ada', 'Margaret']") context.evaluateScript("var triple = function(value) { return value * 3 }") let tripleNum: JSValue = context.evaluateScript("triple(num)")像 JavaScript 這類動態語言需要動態類型,因此正如最後一行所示,JSContext 裡不同的值都封裝在 JSValue 物件中,包括字符串、數值、數組、函數,甚至 Error、null 與 undefined。JSValue 提供了一系列取得底層值的方法,想要取回上述 tripleNum 的值,只需呼叫對應方法:
//Objective-C NSLog(@"Tripled: %d", [tripleNum toInt32]); // Tripled: 30
//Swift println("Tripled: \(tripleNum.toInt32())") // Tripled: 30透過在 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.objectForKeyedSubscript("names") let initialName = names.objectAtIndexedSubscript(0) println("The first name: \(initialName.toString())") // The first name: Grace由於 Swift 誕生不久,還不能像 Objective-C 那樣自如地使用下標符號,目前只能用 objectForKeyedSubscript() 與 objectAtIndexedSubscript() 等方法。
我們可以把 Foundation 類作為參數,直接從 Objective-C/Swift 代碼調用封裝在 JSValue 中的 JavaScript 函數,這一切又歸功於 JavaScriptCore 的橋接作用。
//Objective-C JSValue *tripleFunction = context[@"triple"]; JSValue *result = [tripleFunction callWithArguments:@[@5] ]; NSLog(@"Five tripled: %d", [result toInt32]);
//Swift let tripleFunction = context.objectForKeyedSubscript("triple") let result = tripleFunction.callWithArguments([5]) println("Five tripled: \(result.toInt32())")JSContext 還有一項絕技:透過設定上下文環境的 exceptionHandler 屬性,可以檢查並記錄語法、類型與運行時錯誤。exceptionHandler 是一個回調處理程序,接收 JSContext 的參照以進行異常處理。
//Objective-C context.exceptionHandler = ^(JSContext *context, JSValue *exception) { NSLog(@"JS Error: %@", exception); }; [context evaluateScript:@"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.evaluateScript("function multiply(value1, value2) { return value1 * value2 ") // JS Error: SyntaxError: Unexpected end of script了解了如何從 JavaScript 環境取值與呼叫函數後,反過來,該如何在 JavaScript 中取得 Objective-C 或 Swift 定義的自訂物件與方法呢?主要有兩種途徑:Blocks 與 JSExport 協議。
Blocks(塊)
在 JSContext 中,若把 Objective-C 代碼塊賦值給一個標識符,JavaScriptCore 會自動將其封裝成 JavaScript 函數,從而在 JS 上使用 Foundation 與 Cocoa 類變得更方便。現在連 CFStringTransform 也能在 JavaScript 上使用了:
//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 evaluateScript:@"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), forKeyedSubscript: "simplifyString") println(context.evaluateScript("simplifyString('?????!')")) // annyeonghasaeyo!需注意的是,Swift 的 @objc_block 只適用於 Objective-C block,對 Swift 閉包無效。要在 JSContext 裡使用閉包,有兩個步驟:一是用 @objc_block 宣告,二是用 unsafeBitCast() 把 Swift 閉包轉換為 AnyObject。
記憶體管理
代碼塊可以捕獲變量參照,而 JSContext 中所有變量的強參照都保留在其中,所以要避免循環強參照。此外,不要在代碼塊中捕獲 JSContext 或任何 JSValue,建議用 [JSContext currentContext] 取得當前 Context,並按需把值當作參數傳入 block。
JSExport 協議
借助 JSExport 協議,也能在 JavaScript 上使用自訂物件。凡是在 JSExport 協議中宣告的實例方法、類方法與屬性,都能自動與 JavaScript 交互。
我們先定義一個遵循 JSExport 子協議 PersonJSExport 的 Person model,再用 JavaScript 從 JSON 建立並填入實例。由於 JavaScriptCore 不支援初始化轉換,我們無法像對待原生 JS 類型那樣寫 var person = new Person(),因此類方法是必須的。
PersonJSExports 與 Person
//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 類後,需先把它導出到 JavaScript 環境,同時匯入 Mustache JS 庫,以便對 Person 物件套用模板。
//Objective-C // export Person class context[@"Person"] = [Person class]; // load Mustache.js NSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil]; [context evaluateScript:mustacheJSString];
//Swift // export Person class context.setObject(Person.self, forKeyedSubscript: "Person") // load Mustache.js if let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) { context.evaluateScript(mustacheJSString) }JavaScript 數據處理
以下是一個 JSON 範例,以及用 JSON 建立新 Person 實例的做法。注意:由於 JavaScript 沒有具名參數,額外的參數名會以駝峰命名法附加到函數名上,因此 Objective-C 的 createWithFirstName:lastName: 在 JS 中變成了 createWithFirstNameLastName()。
//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.objectForKeyedSubscript("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.objectForKeyedSubscript("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