偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

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

移動開發(fā) iOS
本文作者Nate Cook是一位獨(dú)立的Web及移動應(yīng)用開發(fā)者,是繼Mattt大神之后NSHipster的主要維護(hù)者,也是非常知名活躍的Swift博主,并且還是支持自動生成Swift在線文檔的SwiftDoc.org網(wǎng)站創(chuàng)造者。在本文中,他介紹了在Swift中使用JavaScript的方法和技巧,對于iOS和Web應(yīng)用工程師有著非常實(shí)用的價(jià)值,以下為譯文:

本文作者Nate Cook是一位獨(dú)立的Web及移動應(yīng)用開發(fā)者,是繼Mattt大神之后NSHipster的主要維護(hù)者,也是非常知名活躍的Swift博主,并且還是支持自動生成Swift在線文檔的SwiftDoc.org網(wǎng)站創(chuàng)造者。在本文中,他介紹了在Swift中使用JavaScript的方法和技巧,對于iOS和Web應(yīng)用工程師有著非常實(shí)用的價(jià)值,以下為譯文:

在RedMonk發(fā)布的2015年1月編程語言排行榜中,Swift采納率排名迅速飆升,從剛剛面世時(shí)的68位躍至22位,Objective-C仍然穩(wěn)居***0,而JavaScript則憑借著其在iOS平臺上原生體驗(yàn)優(yōu)勢成為了年度最火熱的編程語言。

[[132047]]

而早在2013年蘋果發(fā)布的OS X Mavericks和iOS 7兩大系統(tǒng)中便均已加入了JavaScriptCore框架,能夠讓開發(fā)者輕松、快捷、安全地使用JavaScript語言編寫應(yīng)用。不論叫好叫罵,JavaScript霸主地位已成事實(shí)。開發(fā)者們趨之若鶩,JS工具資源層出不窮,用于OS

X和iOS系統(tǒng)等高速虛擬機(jī)也蓬勃發(fā)展起來。

JSContext/JSValue

JSContext即JavaScript代碼的運(yùn)行環(huán)境。一個(gè)Context就是一個(gè)JavaScript代碼執(zhí)行的環(huán)境,也叫作用域。當(dāng)在瀏覽器中運(yùn)行JavaScript代碼時(shí),JSContext就相當(dāng)于一個(gè)窗口,能輕松執(zhí)行創(chuàng)建變量、運(yùn)算乃至定義函數(shù)等的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', 'Ada', 'Margaret']"
  5. context.evaluateScript("var triple = function(value) { return value * 3 }"
  6. let tripleNum: JSValue = context.evaluateScript("triple(num)"

像JavaScript這類動態(tài)語言需要一個(gè)動態(tài)類型(Dynamic Type), 所以正如代碼***一行所示,JSContext里不同的值均封裝在JSValue對象中,包括字符串、數(shù)值、數(shù)組、函數(shù)等,甚至還有Error以及null和undefined。

JSValue包含了一系列用于獲取Underlying Value的方法,如下表所示:

想要檢索上述示例中的tripleNum值,只需使用相應(yīng)的方法即可:

  1. //Objective-C 
  2. NSLog(@"Tripled: %d", [tripleNum toInt32]); 
  3. // Tripled: 30
  1. //Swift 
  2. println("Tripled: \(tripleNum.toInt32())"
  3. // Tripled: 30 

下標(biāo)值(Subscripting Values)

通過在JSContext和JSValue實(shí)例中使用下標(biāo)符號可以輕松獲取上下文環(huán)境中已存在的值。其中,JSContext放入對象和數(shù)組的只能是字符串下標(biāo),而JSValue則可以是字符串或整數(shù)下標(biāo)。

  1. //Objective-C 
  2. JSValue *names = context[@"names"]; 
  3. JSValue *initialName = names[0]; 
  4. NSLog(@"The first name: %@", [initialName toString]); 
  5. // The first name: Grace
  1. //Swift 
  2. let names = context.objectForKeyedSubscript("names"
  3. let initialName = names.objectAtIndexedSubscript(0
  4. println("The first name: \(initialName.toString())"
  5. // The first name: Grace 

而Swift語言畢竟才誕生不久,所以并不能像Objective-C那樣自如地運(yùn)用下標(biāo)符號,目前,Swift的方法僅能實(shí)現(xiàn)objectAtKeyedSubscript()和objectAtIndexedSubscript()等下標(biāo)。

函數(shù)調(diào)用(Calling Functions)

我們可以將Foundation類作為參數(shù),從Objective-C/Swift代碼上直接調(diào)用封裝在JSValue的JavaScript函數(shù)。這里,JavaScriptCore再次發(fā)揮了銜接作用。

  1. //Objective-C 
  2. JSValue *tripleFunction = context[@"triple"]; 
  3. JSValue *result = [tripleFunction callWithArguments:@[@5] ]; 
  4. NSLog(@"Five tripled: %d", [result toInt32]);
  1. //Swift 
  2. let tripleFunction = context.objectForKeyedSubscript("triple"
  3. let result = tripleFunction.callWithArguments([5]) 
  4. println("Five tripled: \(result.toInt32())"

異常處理(Exception Handling)

JSContext還有一個(gè)獨(dú)門絕技,就是通過設(shè)定上下文環(huán)境中exceptionHandler的屬性,可以檢查和記錄語法、類型以及出現(xiàn)的運(yùn)行時(shí)錯(cuò)誤。exceptionHandler是一個(gè)回調(diào)處理程序,主要接收J(rèn)SContext的reference,進(jìn)行異常情況處理。

  1. //Objective-C 
  2. context.exceptionHandler = ^(JSContext *context, JSValue *exception) { 
  3.    NSLog(@"JS Error: %@", exception); 
  4. }; 
  5. [context evaluateScript:@"function multiply(value1, value2) { return value1 * value2 "]; 
  6. // JS Error: SyntaxError: Unexpected end of script 
  1. //Swift 
  2. context.exceptionHandler = { context, exception in 
  3.     println("JS Error: \(exception)"
  4. context.evaluateScript("function multiply(value1, value2) { return value1 * value2 "
  5. // JS Error: SyntaxError: Unexpected end of script 

JavaScript函數(shù)調(diào)用

了解了從JavaScript環(huán)境中獲取不同值以及調(diào)用函數(shù)的方法,那么反過來,如何在JavaScript環(huán)境中獲取Objective-C或者Swift定義的自定義對象和方法呢?要從JSContext中獲取本地客戶端代碼,主要有兩種途徑,分別為Blocks和JSExport協(xié)議。

Blocks (塊)

在JSContext中,如果Objective-C代碼塊賦值為一個(gè)標(biāo)識符,JavaScriptCore就會自動將其封裝在JavaScript函數(shù)中,因而在JavaScript上使用Foundation和Cocoa類就更方便些——這再次驗(yàn)證了JavaScriptCore強(qiáng)大的銜接作用。現(xiàn)在CFStringTransform也能在JavaScript上使用了,如下所示:

  1. //Objective-C 
  2. context[@"simplifyString"] = ^(NSString *input) { 
  3.    NSMutableString *mutableString = [input mutableCopy]; 
  4.    CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO); 
  5.    CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformStripCombiningMarks, NO); 
  6.    return mutableString; 
  7. }; 
  8. NSLog(@"%@", [context evaluateScript:@"simplifyString('?????!')"]);
  1. //Swift 
  2. let simplifyString: @objc_block String -> String = { input in 
  3.     var mutableString = NSMutableString(string: input) as CFMutableStringRef 
  4.     CFStringTransform(mutableString, nil, kCFStringTransformToLatin, Boolean(0)) 
  5.     CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0)) 
  6.     return mutableString 
  7. context.setObject(unsafeBitCast(simplifyString, AnyObject.self), forKeyedSubscript: "simplifyString"
  8. println(context.evaluateScript("simplifyString('?????!')")) 
  9. // annyeonghasaeyo! 

需要注意的是,Swift的speedbump只適用于Objective-C block,對Swift閉包無用。要在一個(gè)JSContext里使用閉包,有兩個(gè)步驟:一是用@objc_block來聲明,二是將Swift的knuckle-whitening unsafeBitCast()函數(shù)轉(zhuǎn)換為 AnyObject。

內(nèi)存管理(Memory Management)

代碼塊可以捕獲變量引用,而JSContext所有變量的強(qiáng)引用都保留在JSContext中,所以要注意避免循環(huán)強(qiáng)引用問題。另外,也不要在代碼塊中捕獲JSContext或任何JSValues,建議使用[JSContext currentContext]來獲取當(dāng)前的Context對象,根據(jù)具體需求將值當(dāng)做參數(shù)傳入block中。

JSExport協(xié)議

借助JSExport協(xié)議也可以在JavaScript上使用自定義對象。在JSExport協(xié)議中聲明的實(shí)例方法、類方法,不論屬性,都能自動與JavaScrip交互。文章稍后將介紹具體的實(shí)踐過程。

JavaScriptCore實(shí)踐

我們可以通過一些例子更好地了解上述技巧的使用方法。先定義一個(gè)遵循JSExport子協(xié)議PersonJSExport的Person model,再用JavaScript在JSON中創(chuàng)建和填入實(shí)例。有整個(gè)JVM,還要NSJSONSerialization干什么?

PersonJSExports和Person

Person類執(zhí)行的PersonJSExports協(xié)議具體規(guī)定了可用的JavaScript屬性。,在創(chuàng)建時(shí),類方法必不可少,因?yàn)镴avaScriptCore并不適用于初始化轉(zhuǎn)換,我們不能像對待原生的JavaScript類型那樣使用var person = new Person()。

  1. //Objective-C 
  2. // in Person.h ----------------- 
  3. @class Person; 
  4. @protocol PersonJSExports     @property (nonatomic, copy) NSString *firstName; 
  5.     @property (nonatomic, 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     @property (nonatomic, copy) NSString *firstName; 
  12.     @property (nonatomic, copy) NSString *lastName; 
  13.     @property NSInteger ageToday; 
  14. @end 
  15. // in Person.m ----------------- 
  16. @implementation Person 
  17. - (NSString *)getFullName { 
  18.     return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName]; 
  19. + (instancetype) createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName { 
  20.     Person *person = [[Person alloc] init]; 
  21.     person.firstName = firstName; 
  22.     person.lastName = lastName; 
  23.     return person; 
  24. @end 
  1. //Swift 
  2. // Custom protocol must be declared with `@objc` 
  3. @objc protocol PersonJSExports : JSExport { 
  4.     var firstName: String { get set } 
  5.     var lastName: String { get set } 
  6.     var birthYear: NSNumber? { get set } 
  7.     func getFullName() -> String 
  8.     /// create and return a new Person instance with `firstName` and `lastName` 
  9.     class func createWithFirstName(firstName: String, lastName: String) -> Person 
  10. // Custom class must inherit from `NSObject` 
  11. @objc class Person : NSObject, PersonJSExports { 
  12.     // properties must be declared as `dynamic` 
  13.     dynamic var firstName: String 
  14.     dynamic var lastName: String 
  15.     dynamic var birthYear: NSNumber? 
  16.     init(firstName: String, lastName: String) { 
  17.         self.firstName = firstName 
  18.         self.lastName = lastName 
  19.     } 
  20.     class func createWithFirstName(firstName: String, lastName: String) -> Person { 
  21.         return Person(firstName: firstName, lastName: lastName) 
  22.     } 
  23.     func getFullName() -> String { 
  24.         return "\(firstName) \(lastName)" 
  25.     } 

配置JSContext

創(chuàng)建Person類之后,需要先將其導(dǎo)出到JavaScript環(huán)境中去,同時(shí)還需導(dǎo)入Mustache JS庫,以便對Person對象應(yīng)用模板。

  1. //Objective-C 
  2. // export Person class 
  3. context[@"Person"] = [Person class]; 
  4. // load Mustache.js 
  5. NSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil]; 
  6. [context evaluateScript:mustacheJSString];
  1. //Swift 
  2. // export Person class 
  3. context.setObject(Person.self, forKeyedSubscript: "Person"
  4. // load Mustache.js 
  5. if let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) { 
  6.     context.evaluateScript(mustacheJSString) 

JavaScript數(shù)據(jù)&處理

以下簡單列出一個(gè)JSON范例,以及用JSON來創(chuàng)建新Person實(shí)例。

注意:JavaScriptCore實(shí)現(xiàn)了Objective-C/Swift的方法名和JavaScript代碼交互。因?yàn)镴avaScript沒有命名好的參數(shù),任何額外的參數(shù)名稱都采取駝峰命名法(Camel-Case),并附加到函數(shù)名稱上。在此示例中,Objective-C的方法createWithFirstName:lastName:在JavaScript中則變成了createWithFirstNameLastName()。

  1. //JSON 
  2.     { "first""Grace",     "last""Hopper",   "year"1906 }, 
  3.     { "first""Ada",       "last""Lovelace""year"1815 }, 
  4.     { "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.         var person = Person.createWithFirstNameLastName(data[i].first, data[i].last); 
  7.         person.birthYear = data[i].year; 
  8.         people.push(person); 
  9.     } 
  10.     return people; 

動手一試

現(xiàn)在你只需加載JSON數(shù)據(jù),并在JSContext中調(diào)用,將其解析到Person對象數(shù)組中,再用Mustache模板渲染即可:

  1. //Objective-C 
  2. // get JSON string 
  3. NSString *peopleJSON = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil]; 
  4. // get load function 
  5. JSValue *load = context[@"loadPeopleFromJSON"]; 
  6. // call with JSON and convert to an NSArray 
  7. JSValue *loadResult = [load callWithArguments:@[peopleJSON]]; 
  8. NSArray *people = [loadResult toArray]; 
  9. // get rendering function and create template 
  10. JSValue *mustacheRender = context[@"Mustache"][@"render"]; 
  11. NSString *template = @"{{getFullName}}, born {{birthYear}}"
  12. // loop through people and render Person object as string 
  13. for (Person *person in people) { 
  14.    NSLog(@"%@", [mustacheRender callWithArguments:@[template, person]]); 
  15. // Output: 
  16. // Grace Hopper, born 1906 
  17. // Ada Lovelace, born 1815 
  18. // Margaret Hamilton, born 1936 
  1. //Swift 
  2. // get JSON string 
  3. if let peopleJSON = NSString(contentsOfFile:..., encoding: NSUTF8StringEncoding, error: nil) { 
  4.     // get load function 
  5.     let load = context.objectForKeyedSubscript("loadPeopleFromJSON"
  6.     // call with JSON and convert to an array of `Person` 
  7.     if let people = load.callWithArguments([peopleJSON]).toArray() as? [Person] { 
  8.         // get rendering function and create template 
  9.         let mustacheRender = context.objectForKeyedSubscript("Mustache").objectForKeyedSubscript("render"
  10.         let template = "{{getFullName}}, born {{birthYear}}" 
  11.         // loop through people and render Person object as string 
  12.         for person in people { 
  13.             println(mustacheRender.callWithArguments([template, person])) 
  14.         } 
  15.     } 
  16. // Output: 
  17. // Grace Hopper, born 1906 
  18. // Ada Lovelace, born 1815 
  19. // Margaret Hamilton, born 1936 
責(zé)任編輯:chenqingxiang 來源: codeceo
相關(guān)推薦

2023-05-16 15:32:45

JavaScriptWeb前端工程師

2014-08-01 15:16:05

SwiftC語言

2009-06-24 10:49:08

Unix

2010-10-08 09:42:23

JavaScript方

2019-04-23 15:20:26

JavaScript對象前端

2020-09-14 14:18:05

Vue和React

2012-04-11 10:39:32

Eclipse

2020-06-18 10:26:43

JavaScript開發(fā)技術(shù)

2015-07-06 10:02:57

Swift編譯配置

2022-11-04 09:01:33

SwiftPlottable

2022-11-30 15:01:11

React技巧代碼

2020-06-04 08:17:44

JavaScript延展操作運(yùn)算符開發(fā)

2016-01-25 15:09:22

JavaScriptC程序

2023-10-04 07:25:59

JavaScriptpromises

2015-08-27 09:46:09

swiftAFNetworkin

2021-09-29 06:03:37

JavaScriptreduce() 前端

2011-09-07 09:51:27

Javascript

2014-07-02 09:47:06

SwiftCocoaPods

2021-12-24 08:55:58

蘋果 iOS 15 SwiftUI

2018-11-26 09:20:26

GrailsjQueryDataTables
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號