zoukankan      html  css  js  c++  java
  • iOS开发热更新JSPatch

      JSPatch,只需在项目中引入极小的引擎,就可以使用JavaScript调用任何Objective-C的原生接口,获得脚本语言的能力:动态更新APP,替换项目原生代码修复bug。

      是否有过这样的经历:新版本上线后发现有个严重的bug,可能会导致crash率激增,可能会使网络请求无法发出,这时能做的只是赶紧修复bug然后提交等待漫长的AppStore审核,再盼望用户快点升级,付出巨大的人力和时间成本,才能完成此次bug的修复。

      使用JSPatch可以解决这样的问题,只需在项目中引入JSPatch,就可以在发现bug时下发JS脚本补丁,替换原生方法,无需更新APP即时修复bug。

    @implementation JPTableViewController
    ...
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
      NSString *content = self.dataSource[[indexPath row]];  //可能会超出数组范围导致crash
      JPViewController *ctrl = [[JPViewController alloc] initWithContent:content];
      [self.navigationController pushViewController:ctrl];
    }
    ...
    @end

    上述代码中取数组元素处可能会超出数组范围导致crash。如果在项目里引用了JSPatch,就可以下发JS脚本修复这个bug:

    //JS
    defineClass("JPTableViewController", {
      //instance method definitions
      tableView_didSelectRowAtIndexPath: function(tableView, indexPath) {
        var row = indexPath.row()
        if (self.dataSource().length > row) {  //加上判断越界的逻辑
          var content = self.dataArr()[row];
          var ctrl = JPViewController.alloc().initWithContent(content);
          self.navigationController().pushViewController(ctrl);
        }
      }
    }, {})

      这样 JPTableViewController 里的 -tableView:didSelectRowAtIndexPath: 就替换成了这个JS脚本里的实现,在用户无感知的情况下修复了这个bug。

    原理

      JSPatch用iOS内置的JavaScriptCore.framework作为JS引擎,但没有用它JSExport的特性进行JS-OC函数互调,而是通过Objective-C Runtime,从JS传递要调用的类名函数名到Objective-C,再使用NSInvocation动态调用对应的OC方法。

      JSPatch更符合Apple的规则。iOS Developer Program License Agreement里3.3.2提到不可动态下发可执行代码,但通过苹果JavaScriptCore.framework或WebKit执行的代码除外,JS正是通过JavaScriptCore.framework执行的。

    动态更新方案对比:JSPatch vs React Native

  • 相关阅读:
    入门训练 圆的面积
    入门训练 序列求和
    interface
    Horizon
    H903
    Sphinx Building Docs in horizon
    Cinder Columns
    DevStack添加Swift
    Murano py27和py34的兼容处理
    Murano Weekly Meeting 2015.12.01
  • 原文地址:https://www.cnblogs.com/WJJ-Dream/p/5809092.html
Copyright © 2011-2022 走看看