天天看点

iOS热更思路学习

JsPatch实现的内部原理概述:

      JsPatch能做到通过JS调用和改写OC方法最根本的原因是 Objective-C 是动态语言,OC上所有方法的调用/类的生成都通过 Objective-C Runtime 在运行时进行,我们可以通过类名和方法名反射得到相应的类和方法,也可以替换某个类的方法为新的实现,还可以新注册一个类,为类添加方法。

      所以 JSPatch 的原理就是:JS传递字符串给OC,OC通过 Runtime 接口调用和替换OC方法。这个很容易理解,JS的作用只是一个信使的作用,具体实现还是得靠OC完成。

由于对JSPatch不熟,一开始就碰到许多OC转JS的错误。

提供两个转换工具的地址:

https://github.com/bang590/JSPatchConvertor

http://jspatch.com/Tools/convertor

转换工具毕竟只是工具,会出现转换问题也是不可避免的,多数还是可以转换正确的。有时间还是自己研究一下,熟悉就会好了。

记录我的学习过程:

首先下载JSPatch导入项目并配置,添加两个库如下:

iOS热更思路学习
iOS热更思路学习

如果需要的功能不多的话,可以只导入JPEngine.h,JPEngine.m和JSPatch.js即可。

在appdelegate中开启:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [JPEngine startEngine];
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo1" ofType:@"js"];
    NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
    if(script){
        [JPEngine evaluateScript:script];
    }

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor    = [UIColor whiteColor];
    self.window.rootViewController = [ViewController new];
    [self.window makeKeyAndVisible];

    return YES;
}

           

ViewController中添加视图

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view addSubview:[self genView]];
}

- (UIView *)genView
{
    UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(, , , )];
    tmpView.backgroundColor = [UIColor greenColor];
    return tmpView;
}

           

效果图:

iOS热更思路学习

UIView的创建:

/*创建view的方式一*/
require('UIView,UIColor');
defineClass('ViewController', {
            genView: function() {
            var tmpView = UIView.alloc().initWithFrame({x:, y:, width:, height:});
            tmpView.setBackgroundColor(UIColor.redColor());
            return tmpView;
            }
            });
           
/*创建view的方式二*/
defineClass('ViewController', {
            genView: function() {
            var tmpView = require('UIView').alloc().init();
            tmpView.setFrame({x:, y:, width:, height:});
            tmpView.setBackgroundColor(require('UIColor').redColor());
            return tmpView;
            }
            });
           

通过require引用相关组件,就会创建一个全局的对象再调取相关的方法即可。

执行js后的效果图:

iOS热更思路学习

参考地址:

http://blog.cnbang.net/works/2767/

http://www.jianshu.com/p/41ed877aa0cd

https://github.com/bang590/JSPatch

继续阅读