之前一直就聽聞JSPath的強大,是上線熱更新的好幫手,不過一直沒去窺探,今日正好閑來無事,擼了個小Demo,著實讓我吃驚,實在太強大了,不僅可以用來修復Bug,同時也可以增加功能,反正能執行你的代碼,想怎么玩就看你需求和想象了。
創建JSPath賬號
- 進入JSPath官網
- 注冊賬號
- 添加App,并且拷貝appkey
在項目中集成JSPath
- 集成方法很簡單,按照官網操作
- 設置Appkey,代碼如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[JSPatch startWithAppKey:@"eff82c1659bf1976"];
[JSPatch sync];
return YES;
}
原來有bug的代碼
demo很簡單,一個UINavigationController裝這一個UITableViewController
#import "ViewController.h"
@interface ViewController ()
{
NSArray *_dataSource;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*這里讓線程睡眠2秒,因為jspath是通過網絡下發代碼,
*這個工程一啟動就執行當前代碼,但是js文件還沒下載下來,就直接崩潰了*/
[NSThread sleepForTimeInterval:2];
_dataSource=@[@"1??",@"2??",@"3??",@"4??",@"???",@"6??",];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId=@"cellId";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
if(cell==nil)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
//這里會報錯,我的素組只有6個元素,但是uitableview有10行
cell.textLabel.text=_dataSource[indexPath.row];
return cell;
}
@end
現在運行立馬崩潰,因為數組越界了
1.png
使用JSPath熱修復
- 編寫js代碼,并且命名為main.js(官方要求),JSPath的語法看官方文檔,js代碼如下
defineClass("ViewController", {
tableView_cellForRowAtIndexPath: function(tableView, indexPath) {
var cellId='cellId';
var cell=tableView.dequeueReusableCellWithIdentifier(cellId);
if(cell==0)
{
cell=require('UITableViewCell').alloc().initWithStyle_reuseIdentifier(0,cellId);
}
var row = indexPath.row()
var datasource=self.valueForKey('_dataSource');
if (datasource.count() > row) { //加上判斷越界的邏輯
cell.textLabel().setText(datasource.objectAtIndex(row));
}
return cell;
}
}
)
defineClass("ViewController", {
tableView_didSelectRowAtIndexPath: function(tableView, indexPath){
//聲明類,使用OC類都需要先聲明才可以使用
require('UIViewController,UIColor');
//創建控制器
var vc=UIViewController.alloc().init();
vc.setTitle("JSPath");
vc.view().setBackgroundColor(UIColor.whiteColor());
//跳轉新的控制器
self.navigationController().pushViewController_animated(vc,1);
//打印日志
console.log(indexPath);
}
})```
是的,我不僅修復了數組越界崩潰的代碼,還畫蛇添足加來點擊cell Push一個控制器的功能。
- 上傳js代碼
- 登錄JSPath
- 進入我的“我的App”頁面
- 選擇添加的app,點擊【管理】
- 點擊【添加App版本】。(注意:版本號必須和線上app版本號一致,否則沒用)
- 上傳js文件
###大功告成
再次運行項目,不需要改任何代碼,就可以達到期望的要求了

###調試模式
在調試的時候,可以把main.js直接拖到項目,并且在appdelegate 配置JSPath調試模式,這樣的話,就不會去線上請求代碼,而是直接運行你本地的js文件。修改后的代碼如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
// [JSPatch startWithAppKey:@"eff82c1659bf1976"];
// [JSPatch sync];
[JSPatch testScriptInBundle]; //開啟調試模式
return YES;
}
### 題外話
到了這里,你是不是覺得挺震驚,同時也感覺挺危險,在后臺幾句JS代碼就可以控制器你的線上App,萬一js文件被攔截了呢?那豈不是為所欲為啦?
不過不用擔心,JSPath為我們提供了加密方式,在上次js文件的時候可以選擇“使用RSA Key” 進行加密。總體來說,我覺得這個技術還是挺不錯的,值得學習,值得使用。