微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Swift中使用JavaScript的方法和技巧


在RedMonk发布的2015年1月编程语言排行榜中,Swift采纳率排名迅速飙升,从刚刚面世时的68位跃至22位,Objective-C仍然稳居TOP 10,而JavaScript则凭借着其在iOS平台上原生体验优势成为了年度最火热的编程语言。

而早在2013年苹果发布的OS X Mavericks和iOS 7两大系统中便均已加入了JavaScriptCore框架,能够让开发者轻松、快捷、安全地使用JavaScript语言编写应用。不论叫好叫骂,JavaScript霸主地位已成事实。开发者们趋之若鹜,JS工具资源层出不穷,用于OS
X和iOS系统等高速虚拟机也蓬勃发展起来。


jscontext/JSValue
jscontext即JavaScript代码的运行环境。一个Context就是一个JavaScript代码执行的环境,也叫作用域。当在浏览器中运行JavaScript代码时,jscontext就相当于一个窗口,能轻松执行创建变量、运算乃至定义函数等的JavaScript代码
  1. //Objective-C
  2. jscontext *context = [[jscontext alloc] init];
  3. [context evaluateScript:@"var num = 5 + 5"];
  4. [context evaluateScript:@"var names = ['Grace','Ada','Margaret']"];
  5. [context evaluateScript:@"var triple = function(value) { return value * 3 }"];
  6. JSValue *tripleNum = [context evaluateScript:@"triple(num)"];
复制代码
  1. //Swift
  2. let context = jscontext()
  3. context.evaluateScript("var num = 5 + 5")
  4. context.evaluateScript("var names = ['Grace','Margaret']")
  5. context.evaluateScript("var triple = function(value) { return value * 3 }")
  6. let tripleNum: JSValue = context.evaluateScript("triple(num)")
像JavaScript这类动态语言需要一个动态类型(Dynamic Type), 所以正如代码最后一行所示,jscontext里不同的值均封装在JSValue对象中,包括字符串、数值、数组、函数等,甚至还有Error以及null和undefined。
JSValue包含了一系列用于获取Underlying Value的方法,如下表所示:

JavaScript Type
JSValue method
Objective-C Type
Swift Type
string
toString
Nsstring
String!
boolean
toBool
BOOL
Bool
number
toNumbertodoubletoInt32
toUInt32

NSNumberdoubleint32_t
uint32_t

NSNumber!DoubleInt32
UInt32

Date
toDate
NSDate
NSDate!
Array
toArray
NSArray
[AnyObject]!
Object
toDictionary
NSDictionary
[NSObject : AnyObject]!
toObjecttoObjectOfClass:
custom type
custom type
想要检索上述示例中的tripleNum值,只需使用相应的方法即可:
  1. NSLog(@"Tripled: %d",[tripleNum toInt32]);
  2. // Tripled: 30
复制代码
  1. println("Tripled: \(tripleNum.toInt32())")
  2. 下标值(Subscripting Values)
    通过在jscontext和JSValue实例中使用下标符号可以轻松获取上下文环境中已存在的值。其中,jscontext放入对象和数组的只能是字符串下标,而JSValue则可以是字符串或整数下标。
    1. JSValue *names = context[@"names"];
    2. JSValue *initialName = names[0];
    3. NSLog(@"The first name: %@",[initialName toString]);
    4. // The first name: Grace
    1. let names = context.objectForKeyedSubscript("names")
    2. let initialName = names.objectAtIndexedSubscript(0)
    3. println("The first name: \(initialName.toString())")
    4. 而Swift语言毕竟才诞生不久,所以并不能像Objective-C那样自如地运用下标符号,目前,Swift的方法仅能实现objectAtKeyedSubscript()和objectAtIndexedSubscript()等下标。
      函数调用(Calling Functions)
      我们可以将Foundation类作为参数,从Objective-C/Swift代码上直接调用封装在JSValue的JavaScript函数。这里,JavaScriptCore再次发挥了衔接作用。
      1. JSValue *tripleFunction = context[@"triple"];
      2. JSValue *result = [tripleFunction callWithArguments:@[@5] ];
      3. NSLog(@"Five tripled: %d",[result toInt32]);
      1. let tripleFunction = context.objectForKeyedSubscript("triple")
      2. let result = tripleFunction.callWithArguments([5])
      3. println("Five tripled: \(result.toInt32())")
      异常处理(Exception Handling)
      jscontext还有一个独门绝技,就是通过设定上下文环境中exceptionHandler的属性,可以检查和记录语法、类型以及出现的运行时错误。exceptionHandler是一个回调处理程序,主要接收jscontext的reference,进行异常情况处理。

      1. context.exceptionHandler = ^(jscontext *context,JSValue *exception) {
      2. NSLog(@"JS Error: %@",exception);
      3. };
      4. [context evaluateScript:@"function multiply(value1,value2) { return value1 * value2 "];
      5. // JS Error: SyntaxError: Unexpected end of script
      1. context.exceptionHandler = { context,exception in
      2. println("JS Error: \(exception)")
      3. }
      4. context.evaluateScript("function multiply(value1,value2) { return value1 * value2 ")
      5. JavaScript函数调用
        了解了从JavaScript环境中获取不同值以及调用函数方法,那么反过来,如何在JavaScript环境中获取Objective-C或者Swift定义的自定义对象和方法呢?要从jscontext获取本地客户端代码,主要有两种途径,分别为Blocks和J**port协议。
        Blocks (块)
        jscontext中,如果Objective-C代码块赋值为一个标识符,JavaScriptCore就会自动将其封装在JavaScript函数中,因而在JavaScript上使用Foundation和Cocoa类就更方便些——这再次验证了JavaScriptCore强大的衔接作用。现在CFStringTransform也能在JavaScript上使用了,如下所示:
        1. context[@"simplifyString"] = ^(Nsstring *input) {
        2. NSMutableString *mutableString = [input mutablecopy];
        3. CFStringTransform((__bridge CFMutableStringRef)mutableString,NULL,kcfStringTransformToLatin,NO);
        4. return mutableString;
        5. NSLog(@"%@",[context evaluateScript:@"simplifyString('안녕하새요!')"]);
        1. let simplifyString: @objc_block String -> String = { input in
        2. var mutableString = NSMutableString(string: input) as CFMutableStringRef
        3. CFStringTransform(mutableString,nil,Boolean(0))
        4. return mutableString
        5. println(context.evaluateScript("simplifyString('안녕하새요!')"))
        6. // 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中。
        J**port协议
        借助J**port协议也可以在JavaScript上使用自定义对象。在J**port协议中声明的实例方法、类方法,不论属性,都能自动与JavaScrip交互。文章稍后将介绍具体的实践过程。
        JavaScriptCore实践
        我们可以通过一些例子更好地了解上述技巧的使用方法。先定义一个遵循J**port子协议PersonJ**port的Person model,再用JavaScript在JSON中创建和填入实例。有整个JVM,还要NSJSONSerialization干什么?
        PersonJ**ports和Person
        Person类执行的PersonJ**ports协议具体规定了可用的JavaScript属性。,在创建时,类方法必不可少,因为JavaScriptCore并不适用于初始化转换,我们不能像对待原生的JavaScript类型那样使用var person = new Person()。
        1. // in Person.h -----------------
        2. @class Person;
        3. @protocol PersonJ**ports <J**port>
        4. @property (nonatomic,copy) Nsstring *firstName;
        5. copy) Nsstring *lastName;
        6. @property NSInteger agetoday;
        7. - (Nsstring *)getFullName;
        8. // create and return a new Person instance with `firstName` and `lastName`
        9. + (instancetype)createWithFirstName:(Nsstring *)firstName lastName:(Nsstring *)lastName;
        10. @end
        11. @interface Person : NSObject <PersonJ**ports>
        12. // in Person.m -----------------
        13. @implementation Person
        14. - (Nsstring *)getFullName {
        15. + (instancetype) createWithFirstName:(Nsstring *)firstName lastName:(Nsstring *)lastName {
        16. Person *person = [[Person alloc] init];
        17. person.firstName = firstName;
        18. return person;
        19. @end
        1. // Custom protocol must be declared with `@objc`
        2. @objc protocol PersonJ**ports : J**port {
        3. var firstName: String { get set }
        4. var lastName: String { get set }
        5. var birthYear: NSNumber? { get set }
        6. func getFullName() -> String
        7. /// create and return a new Person instance with `firstName` and `lastName`
        8. class func createWithFirstName(firstName: String,lastName: String) -> Person
        9. // Custom class must inherit from `NSObject`
        10. @objc class Person : NSObject,PersonJ**ports {
        11. // properties must be declared as `dynamic`
        12. dynamic var firstName: String
        13. dynamic var lastName: String
        14. dynamic var birthYear: NSNumber?
        15. init(firstName: String,lastName: String) {
        16. self.firstName = firstName
        17. }
        18. return Person(firstName: firstName,lastName: lastName)
        19. func getFullName() -> String {
        20. return "\(firstName) \(lastName)"
        21. }
        配置jscontext
        1. // export Person class
        2. context[@"Person"] = [Person class];
        3. // load Mustache.js
        4. Nsstring *mustacheJsstring = [Nsstring stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
        5. [context evaluateScript:mustacheJsstring];
        1. if let mustacheJsstring = String(contentsOfFile:...,encoding:NSUTF8StringEncoding,error:nil) {
        2. context.evaluateScript(mustacheJsstring)
        3. JavaScript数据&处理
          以下简单列出一个JSON范例,以及用JSON来创建新Person实例。
          注意:JavaScriptCore实现了Objective-C/Swift的方法名和JavaScript代码交互。因为JavaScript没有命名好的参数,任何额外的参数名称都采取驼峰命名法(Camel-Case),并附加到函数名称上。在此示例中,Objective-C的方法createWithFirstName:lastName:在JavaScript中则变成了createWithFirstNameLastName()。
          1. //JSON
          2. [
          3. { "first": "Grace","last": "Hopper","year": 1906 },
          4. { "first": "Ada","last": "lovelace","year": 1815 },serif; font-size:12px; line-height:1.8em"> { "first": "Margaret","last": "Hamilton","year": 1936 }
          5. ]
          1. //JavaScript
          2. var loadPeopleFromJSON = function(jsonString) {
          3. var data = JSON.parse(jsonString);
          4. var people = [];
          5. for (i = 0; i < data.length; i++) {
          6. person.birthYear = data[i].year;
          7. people.push(person);
          8. return people;
          9. 动手一试
            现在你只需加载JSON数据,并在jscontext调用,将其解析到Person对象数组中,再用Mustache模板渲染即可:
            1. // get JSON string
            2. Nsstring *peopleJSON = [Nsstring stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
            3. // get load function
            4. JSValue *load = context[@"loadPeopleFromJSON"];
            5. // call with JSON and convert to an NSArray
            6. JSValue *loadResult = [load callWithArguments:@[peopleJSON]];
            7. NSArray *people = [loadResult toArray];
            8. // get rendering function and create template
            9. JSValue *mustacheRender = context[@"Mustache"][@"render"];
            10. Nsstring *template = @"{{getFullName}},born {{birthYear}}";
            11. // loop through people and render Person object as string
            12. for (Person *person in people) {
            13. NSLog(@"%@",[mustacheRender callWithArguments:@[template,person]]);
            14. // Output:
            15. // Grace Hopper,born 1906
            16. // Ada lovelace,born 1815
            17. // Margaret Hamilton,born 1936
            1. if let peopleJSON = Nsstring(contentsOfFile:...,encoding: NSUTF8StringEncoding,error: nil) {
            2. // get load function
            3. let load = context.objectForKeyedSubscript("loadPeopleFromJSON")
            4. // call with JSON and convert to an array of `Person`
            5. if let people = load.callWithArguments([peopleJSON]).toArray() as? [Person] {
            6. // get rendering function and create template
            7. let mustacheRender = context.objectForKeyedSubscript("Mustache").objectForKeyedSubscript("render")
            8. let template = "{{getFullName}},born {{birthYear}}"
            9. // loop through people and render Person object as string
            10. for person in people {
            11. println(mustacheRender.callWithArguments([template,person]))
            12. 版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

        相关推荐