JSPatch 是 GitHub 上一個開源框架,它能透過 Objective-C 的 runtime 機制,用 JavaScript 動態呼叫與替換專案中的 Objective-C 屬性與方法。框架體積小、程式碼簡潔,而且因為是走系統的 JavaScriptCore 與 Objective-C 溝通,在安全性與審核風險上都有不小的優勢。原始碼:https://github.com/bang590/JSPatch。
一、從官方小 demo 看起
用 CocoaPods 把 JSPatch 整合進 Xcode 專案,在 AppDelegate 中寫入:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //啟動引擎 [JPEngine startEngine]; //讀取 js 檔 NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"]; NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil]; //執行 js 檔 [JPEngine evaluateScript:script]; self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; self.window.rootViewController = [[ViewController alloc]init]; [self.window addSubview:[self genView]]; [self.window makeKeyAndVisible]; return YES; } - (UIView *)genView { UIView * view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)]; view.backgroundColor = [UIColor redColor]; return view; }
在專案中加入一個 js 檔:
require('UIView, UIColor, UILabel') //要替換的類 defineClass('AppDelegate', { //替換方法 //要替換的方法名稱 genView: function() { var view = self.ORIGgenView(); view.setBackgroundColor(UIColor.greenColor()) var label = UILabel.alloc().initWithFrame(view.frame()); label.setText("JSPatch"); label.setTextAlignment(1); view.addSubview(label); return view; } });
執行後會看到 genView 已被 JS 版本取代,原本紅色的視圖變成綠色。
二、用 JavaScript 動態修改或新增 Objective-C 方法
JSPatch 支援三種載入 JS 的方式:直接執行字串、讀取本地檔案、抓取網路檔案。例如想用 JS 彈出一個警告框,在 Objective-C 中插入:
- (void)viewDidLoad { [super viewDidLoad]; // ‘\' 用於換行 [JPEngine evaluateScript:@"\ var alertView = require('UIAlertView').alloc().init();\ alertView.setTitle('Alert');\ alertView.setMessage('AlertView from js'); \ alertView.addButtonWithTitle('OK');\ alertView.show(); \ "]; }
也可以動態為既有類添加方法,例如在 ViewController 中:
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [JPEngine startEngine]; NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"]; NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil]; [JPEngine evaluateScript:script]; [self performSelectorOnMainThread:@selector(creatView) withObject:nil waitUntilDone:nil]; }
對應的 JS 檔:
require('UIView, UIColor, UILabel') defineClass('ViewController', { // 新增方法 creatView: function() { var view = UIView.alloc().initWithFrame({x:20, y:20, width:100, height:100}); view.setBackgroundColor(UIColor.greenColor()); var label = UILabel.alloc().initWithFrame({x:0, y:0, width:100, height:100}); label.setText("JSPatch"); label.setTextAlignment(1); view.addSubview(label); self.view().addSubview(view) } });
注意 ViewController.m 裡完全沒有 creatView 這個方法,執行時卻不會崩潰,方法照樣被調用。
由此可見 JSPatch 能做的事相當有趣。iOS App 上架必須經過人工審核,週期有時很長;一旦上線後發現小 bug,想改就相當頭痛。有了 JSPatch,如果能定位到線上有問題的方法,用一份 JS 檔把它替換掉,這個問題就解決了——事實上,線上小問題的 hotfix 正是它最主要的用途。
三、JavaScript 與 Objective-C 互動的基礎規則
1. 在 JS 中使用 Objective-C 類
使用前必須先 require:
require('UIView')
也可以一次引用多個:
require('UIView, UIColor, UILabel')
還有一種更簡便的寫法,邊用邊引用:
require('UIView').alloc().init()
2. 呼叫 Objective-C 方法
類方法用「類名打点」的方式呼叫:
UIColor.redColor()
實例方法則是「物件打点」:
view.addSubview(label)
多參數方法在轉為 JS 時,以 _ 標記參數切分位置,參數全部放進後面的括號並以逗號分隔:
view.setBackgroundColor(UIColor.colorWithRed_green_blue_alpha(0,0.5,0.5,1))
屬性變數在 JS 中只能用 getter/setter 存取:
label.setText("JSPatch")
提示:若原本的 Objective-C 方法名已含 _,在 JS 中要改用 __ 代替。
3. 操作與修改 Objective-C 類
用 defineClass 定義或修改類的方法:
/* classDeclaration:要新增或重寫方法的類名(字串),若此類不存在則會建立新類 instanceMethods:要新增或重寫的實例方法 {} classMethods:要新增或重寫的類方法 {} */ defineClass(classDeclaration, instanceMethods, classMethods)
示例:
defineClass('ViewController', { // 新增實例方法 newFunc: function() { self.view().setBackgroundColor(UIColor.redColor()) } },{ // 新增類方法 myLoad:function(){ } } )
若要在重寫後呼叫原方法,加上 ORIG 前綴:
defineClass('ViewController', { viewDidLoad: function() { self.ORIGviewDidLoad() } } )
原本的 super 呼叫則寫成 self.super():
defineClass('ViewController', { viewDidLoad: function() { self.super().viewDidLoad() } } )
JSPatch 也能為類掛上臨時屬性以便在方法間傳值,用 set_Prop_forKey() 寫入、getProp() 取出(注意:這種屬性無法用 Objective-C 的 setter/getter 存取):
defineClass('ViewController', { viewDidLoad: function() { self.super().viewDidLoad() self.setProp_forKey("JSPatch", "data") }, touchesBegan_withEvent(id,touch){ self.getProp("data") self.view().setBackgroundColor(UIColor.redColor()) } } )
宣告遵守協議的寫法與 Objective-C 一致:
defineClass("ViewController2: UIViewController <UIAlertViewDelegate>", { viewDidAppear: function(animated) { var alertView = require('UIAlertView') .alloc() .initWithTitle_message_delegate_cancelButtonTitle_otherButtonTitles( "Alert", "content", self, "OK", null ) alertView.show() }, alertView_clickedButtonAtIndex:function(alertView, buttonIndex) { console.log('clicked index ' + buttonIndex) } })
四、常見型別的轉換
1. 結構體
JSPatch 原生支援 CGPoint、CGSize、CGRect、NSRange 四種結構體,剛好都是做 UI 時最常用的。
CGRect:
var view = require('UIView').alloc().init() view.setFrame({x:100,y:100,width:100,height:100})
CGPoint:
view.setCenter({x:200,y:200})
CGSize:
var size = {width:200,height:200} view.setFrame({x:100,y:100,width:size.width,height:size.height})
NSRange:
var range = {location: 0, length: 1}
2. 選擇器 Selector
用字串表示:
self.performSelector_withObject("func:", 1)
3. 空物件
JS 中的 null 與 undefined 都對應 Objective-C 的 nil;而 Objective-C 的 NSNull 則用 nsnull 表示。
4. block 的雙向互動
在 JS 中呼叫 Objective-C 的 block 很簡單,因為 JS 沒有 block 概念,Objective-C 會自動把它轉成函數:
Objective-C:
typedef void(^block)(NSString * str); @interface ViewController () @end @implementation ViewController -(block)getBlock{ block block = ^(NSString * str){NSLog(@"%@",str);}; return block; } @end
JavaScript:
defineClass("ViewController", { viewDidAppear: function(animated) { var func = self.getBlock() func("123") } })
反過來,把 JS 函數當作 block 傳給 Objective-C 則要用 block() 包裝:
Objective-C:
@interface ViewController () @end @implementation ViewController -(void)run:(void(^)(NSString * str))block{ block(@"123"); } @end
JavaScript:
defineClass("ViewController", { viewDidAppear: function(animated) { // run 方法需要傳入一個 block self.run(block("NSString*",function(str){console.log(str)})) } })
block(param1,param2) 的第一個參數是函式參數型別(多個以逗號分隔),第二個參數是函式主體。
注意:block() 包裝的函式內不可使用 self,若需要請先在外部用臨時變數承接:
defineClass("ViewController", { viewDidAppear: function(animated) { var slf = self self.run(block("NSString*", function(str){ console.log(str) slf.log(str) })) } })
並分別以 __weak() 與 __strong() 宣告弱引用與強引用:
var slf = __weak(self) var stgSef = __strong(self)
5. GCD 與列舉
GCD 的呼叫方式:
//讓當前執行緒停住一段時間 dispatch_after(1.0, function(){ }) //為主線程加入非同步任務 dispatch_async_main(function(){ }) //為主線程加入同步任務 dispatch_sync_main(function(){ }) //向全域佇列加入任務 dispatch_async_global_queue(function(){ })
JSPatch 無法直接使用 Objective-C 中定義的列舉,但可以傳遞其真實數值,例如:
//UIControlEventTouchUpInside 的值是 1<<6 btn.addTarget_action_forControlEvents(self, "handleBtn", 1<<6);
最後提醒一句:正因為 JSPatch 具備動態替換方法的強大能力,App Store 對這類「下發程式碼改變 App 行為」的做法向來審查嚴格,上線前務必確認合規風險。以上就是 JSPatch 的用法整理,希望對你的開發有所幫助。