OC Runtime:
材料文章參考
Runtime
OC運行時的意義在于一切方法的調用不是在編譯時就決定好的沸移,要通過運行時最終決定床牧,非常靈活荣回。
1.運行時動態(tài)檢查該對象及其父對象(dispatch table)是否包含改方法。
2.沒有的話進入動態(tài)方法解析和轉發(fā)階段
2.1 +resolveInstanceMethod: 檢查是否對方法處理戈咳,可通過添加新的方法實現(xiàn)
2.2 -forwardingTargetForSelector: 可將相應方法目標轉發(fā)到其他對象上
2.3-methodSignatureForSelector:最后一次機會生成新的方法簽名調用心软,之后系統(tǒng)生成NSInvocation,可以進一步在-forwardInvocation通過判斷.selector屬性進行相應的invocation的target修改或者方法的直接調用
Swizzle: 相關資料
本質上Swizzle是利用到OC Runtime的第一步中的dispatch table(記錄了objc_method(SEL/char/IMP)) 的互換實現(xiàn)的。
方法替換:
Method originalMethod = class_getInstanceMethod(self, @selector(viewWillAppear:));
Method swizzledMethod = class_getInstanceMethod(self, @selector(fd_viewWillAppear:));
method_exchangeImplementations(originalMethod, swizzledMethod);
替換方法實現(xiàn):
- (void)fd_viewWillAppear:(BOOL)animated
{
// Forward to primary implementation.
[self fd_viewWillAppear:animated];
if (self.fd_willAppearInjectBlock) {
self.fd_willAppearInjectBlock(self, animated);
}
}