目的:指透明的把一個東西換成另一個。在運行時替換兑障。
利用方法混寫可以改變那些沒有源代碼的對象。
該方法大致可以劃分為三種:
1)有可能類已經(jīng)實現(xiàn)的了
2)某個父類實現(xiàn)的方法
3)根本沒有實現(xiàn)
前兩種 可以通過調(diào)用class_getInstanceMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>),成功后會返回一個IMP ,失敗則是NULL。
最后一種 可以通過調(diào)用class_addMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>, <#IMP imp#>, <#const char *types#>) 如果失敗,則此類直接實現(xiàn)了正在混寫的方法泵督,那么轉(zhuǎn)而用method_setImplementation(<#Method m#>, <#IMP imp#>)來把就實現(xiàn)替換為新的實現(xiàn)即可。
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
// ...
// Method originalMethod = class_getClassMethod(class, originalSelector);
// Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}
@end