前言
运行时的的交换方法也叫黑魔法,在许多的第三方框架都使用了,例如AFN等
步骤
一、获得两个需要交换的方法
Method aMethod = class_getClassMethod(self, aSel);
Method bMethod = class_getClassMethod(self, bSel);
二、交换两个方法的实现方式
method_exchangeImplementations(aMethod, bMethod);
例子
场景:UI给的字号与实际有个等比例的关系,于是为了偷懒,我搞了一个交换方法
,给UIFont添加一个分类,并在+load方法里进行交换。为了日后交换方便,我也给NSObject写了一个分类
NSObject分类
@implementation NSObject (Exchange)
+(void)exchangeClassSelector:(SEL)aSel toSelector:(SEL)bSel
{
Method aMethod = class_getClassMethod(self, aSel);
Method bMethod = class_getClassMethod(self, bSel);
method_exchangeImplementations(aMethod, bMethod);
}
UIFont分类:
+(void)load
{
[self exchangeClassSelector:@selector(systemFontOfSize:) toSelector:@selector(fk_systemFontOfSize:)];
}
+ (UIFont *)fk_systemFontOfSize:(CGFloat)fontSize
{
//这里要注意,返回的是“fk_systemFontOfSize:”,因为前面已经交换方法了,所以这里实际调用的是系统的方法
return [self fk_systemFontOfSize:fontSize*11./20];
}