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导入项目并配置,添加两个库如下:
这里写图片描述

这里写图片描述

如果需要的功能不多的话,可以只导入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(0, 0, 320, 320)];
    tmpView.backgroundColor = [UIColor greenColor];
    return tmpView;
}

效果图:
这里写图片描述

UIView的创建:

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

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

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

执行js后的效果图:
这里写图片描述

参考地址:
http://blog.cnbang.net/works/2767/
http://www.jianshu.com/p/41ed877aa0cd
https://github.com/bang590/JSPatch

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值