Objective-C 运行时

2017-12-22  本文已影响3人  yght

OC Runtime:
材料文章参考
Runtime
OC运行时的意义在于一切方法的调用不是在编译时就决定好的,要通过运行时最终决定,非常灵活。
1.运行时动态检查该对象及其父对象(dispatch table)是否包含改方法。
2.没有的话进入动态方法解析和转发阶段
2.1 +resolveInstanceMethod: 检查是否对方法处理,可通过添加新的方法实现
2.2 -forwardingTargetForSelector: 可将相应方法目标转发到其他对象上
2.3-methodSignatureForSelector:最后一次机会生成新的方法签名调用,之后系统生成NSInvocation,可以进一步在-forwardInvocation通过判断.selector属性进行相应的invocation的target修改或者方法的直接调用

objectivec-runtime-overview-39-638.jpg

Swizzle: 相关资料
本质上Swizzle是利用到OC Runtime的第一步中的dispatch table(记录了objc_method(SEL/char/IMP)) 的互换实现的。
方法替换:

    Method originalMethod = class_getInstanceMethod(self, @selector(viewWillAppear:));
    Method swizzledMethod = class_getInstanceMethod(self, @selector(fd_viewWillAppear:));
    method_exchangeImplementations(originalMethod, swizzledMethod);

替换方法实现:

- (void)fd_viewWillAppear:(BOOL)animated
{
    // Forward to primary implementation.
    [self fd_viewWillAppear:animated];
    
    if (self.fd_willAppearInjectBlock) {
        self.fd_willAppearInjectBlock(self, animated);
    }
}
上一篇下一篇

猜你喜欢

热点阅读