- load 方法是在初始化时调用
- 使用单利是为了只执行一遍、
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class cls = [self class];
/// 想要替换的实例方法
SEL originalSelector = @selector(init);
/// 替换的新方法名
SEL swizzledSelector = @selector(x_init);
Method originalMethod = class_getInstanceMethod(cls, originalSelector);
Method swizzlingMethod = class_getInstanceMethod(cls, swizzledSelector);
/// 在交换方法之前要先判断将要替换的方法是否存在
BOOL isExist = class_addMethod(cls, originalSelector, method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));
/// 实现方法交换
if (isExist) {
class_replaceMethod(cls, swizzlingMethod, method_getImplementation(swizzlingMethod), method_getTypeEncode(swizzlingMethod));
} else {
method_exchangeImplementations(originMethod, swizzlingMethod);
}
/// 如果替换的是类方法
Class classB = Object_getClass(self);
// /// 想要替换的类方法
// SEL originalSelector = @selector(array);
// /// 替换的新方法名
// SEL swizzledSelector = @selector(x_array) ;
//
// Method originalMethod = class_getClassMethod(classB, originalSelector);
// Method swizzlingMethod = class_getClassMethod(classB, swizzledSelector);
});
}
网友评论