美文网首页
JSPatch使用笔记(1)

JSPatch使用笔记(1)

作者: SamDing | 来源:发表于2016-10-10 19:12 被阅读218次

    一、背景需求介绍

    为什么我们需要一个热修复(hot-fix)技术?
    • 工作中容易犯错、bug难以避免。
    • 开发和测试人力有限。
    • 苹果Appstore审核周期太长,一旦出现严重bug难以快速上线新版本。
    • 作为生产力工具,用户有对稳定性和可靠性的需求。

    二、JSPatch简介

    JSPatch诞生于2015年5月,最初是腾讯广研高级iOS开发@bang的个人项目。
    它能够使用JavaScript调用Objective-C的原生接口,从而动态植入代码来替换旧代码,以实现修复线上bug。
    JSPatch在Github.com上开源后获得了3000多个star和500多fork,广受关注,目前已被应用在大量腾讯/阿里/百度的App中。

    三、JSPatch与wax对比

    Paste_Image.png

    最关键的是JSPatch可实现方法粒度的线上代码替换,能修复一切代码引起的Bug。而Wax无法实现。

    四、JSPatch实现原理

    有关JSPatch基础原理,请查阅文档地址项目地址

    Usage:
    1.#import "JPEngine.h"
    2.call [JPEngine startEngine]
    3.exec JavasScript by [JPEngine evaluateScript:@""]

    [JPEngine startEngine];
    
    // exec js directly
    [JPEngine evaluateScript:@"\ 
    var alertView = require('UIAlertView').alloc().init();\ 
    alertView.setTitle('Alert');\ 
    alertView.setMessage('AlertView from js'); \ 
    alertView.addButtonWithTitle('OK');\ alertView.show(); \
    "];
    
    // exec js file from network
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cnbang.net/test.js"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
        NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
        [JPEngine evaluateScript:script];
    }];
    
    // exec local js file
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"js"];
    NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
    [JPEngine evaluateScript:script];
    

    JSPatch使用的基础核心部分,就是怎样将你要修复的某各类中的方法用js重写,以替换原来的方法,最终消除bug。第一篇文章主要讲解一下翻译语法,我将通过一个例子来辅助描述JSPatch的基本转化语法。

    以下是一段简单的oc代码,但是发现在跳转到SXMeMoneyDetailViewController时忘记了隐藏bottomBar,现在需要通过JSPatch重写这个方法,将 vc.hidesBottomBarWhenPushed = YES; 这段代码加上
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        
    
            SXMeSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_MeSectionCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof(self) weakSelf = self;
            cell.sectionBlock = ^(NSInteger index){
                if([Login chectLogin]){ 
                    if(index == 4){
                        SXMeMoneyDetailViewController *vc = [[SXMeMoneyDetailViewController alloc] init];
                        //vc.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }
            };
            return cell;
        }
    }
    
    

    补丁js代码如下:

    1. defineClass("SXMeViewController", {
    2.  tableView_cellForRowAtIndexPath: function(tableView, indexPath){
    3.      var cell = tableView.dequeueReusableCellWithIdentifier_forIndexPath("MeSectionCell",indexPath);
    4.      cell.setSelectionStyle(0);
    5.      var weakSelf = __weak(self);
    6.      cell.setSectionBlock(block("NSUInteger",function(index){
    7.          if(index == 4){
    8.              if(require("Login").chectLogin()){
    9.                  var vc = require("SXMeWalletViewController").alloc().init();
    10.                 vc.setHidesBottomBarWhenPushed(1);
    11.                 weakSelf.navigationController().pushViewController_animated(vc,1);
    12.             }
    13.         }
    14。     }));
    15.     return cell;
    16. },
    17. })
    

    上面补丁主要作用是重写SXMeViewController中的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法来修复线上bug

    第一行,第二行:
    defineClass的具体使用api方法请查阅文档,api说明如下:

    defineClass(classDeclaration, [properties,] instanceMethods, classMethods)
    
    @param classDeclaration: 字符串,类名/父类名和Protocol
    @param properties: 新增property,字符串数组,可省略
    @param instanceMethods: 要添加或覆盖的实例方法
    @param classMethods: 要添加或覆盖的类方法
    

    第三行:

    oc:
    SXMeSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_MeSectionCell forIndexPath:indexPath];
    js:
    var cell = tableView.dequeueReusableCellWithIdentifier_forIndexPath("MeSectionCell",indexPath);
    
    

    第一要注意的是语法转换格式,仔细观察可以找到规律,方法传递参数名使用了'_'拼接,参数值在括号里。
    第二点Objective-C 里的常量/枚举不能直接在 JS 上使用,可以直接在 JS 上用具体值代替。例如:

    #define kCellIdentifier_MeSectionCell @"MeSectionCell"
    

    在js中可直接使用其对应数值"MeSectionCell"

    第四行:

    oc:
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    js:
    cell.setSelectionStyle(0);
    

    这里遇到了系统的枚举值,同第三行一样,需要直接使用枚举对应的integer数值

    第五行:

    oc:
    __weak typeof(self) weakSelf = self;
    js:
    var weakSelf = __weak(self);
    

    可以在 JS 通过 __weak()声明一个 weak 变量,主要用于避免循环引用。

    第六行:

    oc:
    cell.sectionBlock = ^(NSInteger index){
    }
    js:
    cell.setSectionBlock(block("NSUInteger",function(index){
    }));
    

    若使用 block 时出现 crash,最常见的原因是在 block 里使用了 self变量,应该在 JS 声明另一个变量持有 self,详情见这里
    另外请详读 block 的传递规则,以及使用 block 的几个限制

    第九行,第十行:
    这两行主要涉及require,和类方法的使用,代码比较清晰,大家自己看吧,有关实例方法,category方法的使用,请看文档

    总结:
    这篇文章简单介绍了JPatch的作用和基本使用方法,接下来的文章将主要总结一下使用经验,常见问题解决方法,以及扩展使用介绍。

    相关文章

      网友评论

          本文标题:JSPatch使用笔记(1)

          本文链接:https://www.haomeiwen.com/subject/fyrvyttx.html