swizzle代码+注释

关于Swizzle网上讲的太多了,需要先知道运行时方法存储结构(Method)。不会的自行google吧。这段代码自己凭着回忆写的。希望没错

+ (void)swizzleSEL:(SEL)originalSEL withSEL:(SEL)swizzledSEL {

//得到类对象

Class class = [selfclass];

//得到SEL对应的结构体(包含IMP和SEL,IMP对应一个SEL)

MethodoriginalMethod =class_getInstanceMethod(class, originalSEL);

MethodswizzledMethod =class_getInstanceMethod(class, swizzledSEL);

//考虑到swizzledSEL如果并未再类中定义,则需要先添加到方法列表中,如果已经定义或失败则返回NO

//新IMP对应原SEL

BOOLdidAddMethod =

class_addMethod(class,

originalSEL,

method_getImplementation(swizzledMethod),

method_getTypeEncoding(swizzledMethod));

//原IMP对应新SEL

if(didAddMethod) {

class_replaceMethod(class,

swizzledSEL,

method_getImplementation(originalMethod),

method_getTypeEncoding(originalMethod));

}else{

//直接交换IMP

method_exchangeImplementations(originalMethod, swizzledMethod);

}

}

具体使用,一般是再load中用

+ (void)load {

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

[self swizzleSEL:@selector(方法1:) withSEL:@selector(方法2:)];


});

}

你可能感兴趣的:(swizzle代码+注释)