JSPatch 是一個開源項目(Github連接),只須要在項目裏引入極小的引擎文件,就能夠使用 JavaScript 調用任何 Objective-C 的原生接口,替換任意 Objective-C 原生方法。目前主要用於下發 JS 腳本替換原生 Objective-C 代碼,實時修復線上 bug。
除了實時修復線上 bug,甚至爲 APP 動態添加一個模塊也是可行的,不過可能會有性能問題。
使用JSPatch 須要有一個後臺能夠下發和管理腳本,而且須要處理傳輸安全等部署工做。
目前有一個JSPatch 平臺提供了一系列的服務,只需引入一個 SDK 就能使用 JSPatch,只是還在內測中....
地址 :https://github.com/bang590/JSPatchphp
CocoPods安裝:ios
Podfile文件git
platform :ios, '6.0'
pod 'JSPatch'github
而後 安全
pod install服務器
下面開始使用:咱們先建立一個列表,再經過JSPath改變行數 app
1.咱們先在Controller里加入一個列表,讓他顯示3行 ,代碼以下:工具
#import "JRViewController.h" @interface JRViewController ()<UITableViewDataSource,UITableViewDelegate> @property(nonatomic,strong)UITableView* myTableView; @end @implementation JRViewController - (void)viewDidLoad { [super viewDidLoad]; UITableView* tv =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain]; self.myTableView = tv; self.myTableView.delegate = self; self.myTableView.dataSource = self; [self.view addSubview:self.myTableView]; } #pragma mark -- UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 3; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString* i= @"cell"; UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:i]; if (cell == nil ) { cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:i]; } cell.textLabel.text = @"title"; return cell; }
運行一下,顯示3行,沒問題性能
2.建立js文件 New File -> ios -> Empty .....ui
3.在js文件中 寫入:
//將JRViewController類中的- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section方法替換掉 defineClass('JRViewController', { tableView_numberOfRowsInSection: function(tableView, section) { return 10; }, });
關於JSPath的具體使用,請自行查閱:https://github.com/bang590/JSPatch/wiki
4.調用這個js文件,代碼以下:
#import "AppDelegate.h" #import "JPEngine.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [JPEngine startEngine]; NSString* path = [[NSBundle mainBundle]pathForResource:@"JSPathTest" ofType:@"js"]; NSString* js = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; [JPEngine evaluateScript:js]; return YES; }
運行一下,如今是顯示10行了 !
注:
若是咱們想要經過 JS 腳本替換原生 Objective-C 代碼,實時修復線上 bug的話,仍是要經過服務器下發 js腳本 !
代碼以下:
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://........"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; [JPEngine evaluateScript:script]; }];