1.為什么要引入JSPatch
相信對于維護已經(jīng)發(fā)版了的IOS的朋友都有遇到過程序已經(jīng)上架了,可是現(xiàn)在突然發(fā)現(xiàn)有一個十分緊急的問題需要修復(fù)。及時我們可以走蘋果的加急通道制轰,但這并不意味著我們可以不走蘋果的審核,整個流程下來也得兩三天己英∏#可是如果我們的項目引入了JSPatch
我們就可以避免這樣的問題發(fā)生肉迫,動態(tài)的修復(fù)APP的bug溺健。
2.淺談JSPatch實現(xiàn)原理
首先需要普及的是:OC是一門動態(tài)運行的語言麦牺,所有的類的創(chuàng)建和方法的調(diào)用都是通過Object-C Runtime
在運行時進行的。JSPathc
就是抓住OC的這一特點鞭缭,以IOS內(nèi)置的JavaScriptCore.framework
作為JS引擎,從JS傳遞要調(diào)用的函數(shù)名和類名到OC,再使用NSInvocation
動態(tài)調(diào)用對應(yīng)的方法魏颓。例:
Class class = NSClassFromString(@"UIViewController");
id controller = [class new];
SEL selector = NSSelectorFromString(@"viewDidLoad");
[controller performSelector:selector];
如果想要深入了解其原理岭辣,可以查看作者的原文章
地址:http://www.csdn.net/article/2015-10-29/2826084
3.簡單搭建JSPath項目
JSPatch
下載地址:https://github.com/wangyansnow/JSPatch
只需要把JSPatch這個文件夾拖入到項目中,然后把github中下載項目的demo.js文件拖入到項目中甸饱。然后在APPDelegate
編寫如下代碼:
#import "AppDelegate.h"
#import "JPEngine.h"
#import "ViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[JPEngine startEngine];
NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"demo.js" ofType:nil];
[JPEngine evaluateScriptWithPath:jsPath];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
ViewController *rootViewController = [[ViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;
}
@end
再在ViewController.m
中編寫如下代碼:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 50)];
[btn setTitle:@"Push JPTableViewController" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(handleBtn:) forControlEvents:UIControlEventTouchUpInside];
[btn setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:btn];
}
- (void)handleBtn:(UIButton *)btn {
}
最后在吧demo.js里面的JPViewController
修改為ViewController
4.最后介紹一個OC代碼轉(zhuǎn)js的網(wǎng)址
只需要在其中輸入OC代碼然后店家Covert即可轉(zhuǎn)換為對應(yīng)的js代碼沦童。【復(fù)雜OC代碼還是需要自己寫對應(yīng)的js】
網(wǎng)址:http://bang590.github.io/JSPatchConvertor/