JSON

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

字号+ 作者:H5之家 来源:H5之家 2017-04-10 12:00 我要评论( )

Nate Cook是一位独立的Web及移动应用开发者,是继Mattt大神后NSHipster的主要维护者,也是SwiftDoc.org创造者。在本文中,他介绍了在Swift中使用JavaScript的方

  • JSExport协议
  • 借助JSExport协议也可以在JavaScript上使用自定义对象。在JSExport协议中声明的实例方法、类方法,不论属性,都能自动与JavaScrip交互。文章稍后将介绍具体的实践过程。

    JavaScriptCore实践

    我们可以通过一些例子更好地了解上述技巧的使用方法。先定义一个遵循JSExport子协议PersonJSExport的Person model,再用JavaScript在JSON中创建和填入实例。有整个JVM,还要NSJSONSerialization干什么?

  • PersonJSExports和Person
  • 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)" } }
  • 配置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实例。

    注意:JavaScriptCore实现了Objective-C/Swift的方法名和JavaScript代码交互。因为JavaScript没有命名好的参数,任何额外的参数名称都采取驼峰命名法(Camel-Case),并附加到函数名称上。在此示例中,Objective-C的方法createWithFirstName:lastName:在JavaScript中则变成了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

    (编译/张新慧 责编/唐小引)

    文章来源:

    点击链接进入Swift技术社区,了解更多Swift开发的技术热点内容!

    本文为CSDN编译整理,未经允许不得转载,如需转载请联系market#csdn.net(#换成@)

    CSDN JOB移动工程师专场招聘,直击20家企业高薪职位-->

     

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    相关文章
    • 动态读取JSON解析键值对的方法

      动态读取JSON解析键值对的方法

      2017-04-10 13:03

    • JS动态遍历json中所有键值对讫方法

      JS动态遍历json中所有键值对讫方法

      2017-04-10 11:02

    • webpack2 和 NPM Scripts 进行 JavaScript 组件开发

      webpack2 和 NPM Scripts 进行 JavaScript 组件开发

      2017-04-01 13:02

    • 自己动手使用 Swift 打造全功能 JSON 解析、生成库

      自己动手使用 Swift 打造全功能 JSON 解析、生成库

      2017-03-29 16:01

    网友点评