Method Swilzzing 方法交换

+(void)load{

static dispatch_once_t onceToken;

dispatch_once(&onceToken,^{

[LGRuntimeTool lg_methodSwizzlingWithClass:selforiSEL:@selector(personInstanceMethod)swizzledSEL:@selector(lg_studentInstanceMethod)];

});

}

+ (void)lg_bestMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{

if (!cls) NSLog(@"传入的交换类不能为空");

Method oriMethod = class_getInstanceMethod(cls, oriSEL);

Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);

if (!oriMethod) {

// 在oriMethod为nil时,替换后将swizzledSEL复制一个不做任何事的空实现,代码如下:

class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod)); method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));

}

// 一般交换方法: 交换自己有的方法 -- 走下面 因为自己有意味添加方法失败 // 交换自己没有实现的方法: // 首先第一步:会先尝试给自己添加要交换的方法 :personInstanceMethod (SEL) -> swiMethod(IMP) // 然后再将父类的IMP给swizzle personInstanceMethod(imp) -> swizzledSEL //oriSEL:personInstanceMethod

BOOL didAddMethod = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));

if (didAddMethod) {

class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));

}else{

method_exchangeImplementations(oriMethod, swiMethod);

}

}

method-swizzling最常用的应用是防止数组、字典等越界崩溃

NSArray --> __NSArrayI

NSMutableArray --> __NSArrayM

NSDictionary --> __NSDictionaryI

NSMutableDictionary --> __NSDictionaryM

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容