关于OC的特性运行时,可以实现黑魔法 Method Swizzling。
![](https://img.haomeiwen.com/i4064463/c45d138dee071e55.jpg)
实现代码举例:
+ (void)load {
Classclz = [selfclass];
SELoldSEL =@selector(viewDidAppear:);
SELnewSEL =@selector(newviewffDidAppear:);
MethodoriginalMethod =class_getInstanceMethod(clz, oldSEL);
MethodswizzledMethod =class_getInstanceMethod(clz, newSEL);
BOOLdidAddMethod =class_addMethod(clz,
oldSEL,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if(didAddMethod) {
class_replaceMethod(clz,
oldSEL,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
- (void) newviewffDidAppear:(BOOL)animated {
[selfnewviewDidAppear:animated];
WRITE_PERFORMANCE
}
网友评论