Runtime
交换系统的方法
在项目中经常会遇到统计用户使用习惯,例如用户进入某个页面的频次,如果在每个页面增加统计的方法那么会增加很多的重复代码,可以使用运行时的特性在分类中交换方法达到目的,交换系统的方法并且不需要重新导入头文件就可以达到,但是如果两个分类分别执行相同的操作去交换同一个方法那么会交换无效,方法名不同只会执行后面的。在不改变原有方法的效果上如果数组中判断控制情况等
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = NSSelectorFromString(@"dealloc");
SEL swizzledSelector = @selector(xxx_dealloc);
// 实列方法 分配在栈上 类方法分配在堆
// class_getClassMethod(<#Class _Nullable __unsafe_unretained cls#>, <#SEL _Nonnull name#>) //获取类防范
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(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);
}
});
}
- (void)xxx_dealloc{
NSLog(@"%s",__func__);
}
SEL、IMP、isa
- isa:类指针,指向类对象
- imp:函数实现指针,指向函数体
- SEL:指向函数名的指针