而早在2013年蘋果發布的OS X Mavericks和iOS 7兩大系統中便均已加入了JavaScriptCore框架,能夠讓開發者輕鬆、快捷、安全地使用JavaScript語言編寫應用程式。不論叫好叫罵,JavaScript霸主地位已成事實。開發者趨之若鶓,JS工具資源層出不窮,用於OS X和iOS系統等高速虛擬機器也蓬勃發展。
//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
let tripleFunction = context.objectForKeyedSubscript("triple")
let result = tripleFunction.callWithArguments([5])
println("Five tripled: \(result.toInt32())")
Person类执行的PersonJSExports协议具体规定了可用的JavaScript属性。,在创建时,类方法必不可少,因为JavaScriptCore并不适用于初始化转换,我们不能像对待原生的JavaScript类型那样使用var person = new Person()。
//Objective-C
// in Person.h -----------------
@class Person;
@protocol PersonJSExports <JSExport>
@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 <PersonJSExports>
@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)"
}
}
//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;
}
//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