新建一个类别,导入#import <objc/runtime.h>
在+ (void)load
方法中写代码
+ (void)load
{
SEL orignsel = @selector(setBackgroundColor:);
SEL exchgesel = @selector(ly_setBackGroundColor:);
Method originalM = class_getInstanceMethod([self class], orignsel);
Method exchangeM = class_getInstanceMethod([self class], exchgesel);
BOOL didAddMethod = class_addMethod([self class], orignsel, method_getImplementation(exchangeM), method_getTypeEncoding(exchangeM));
if (didAddMethod)
{
class_replaceMethod([self class], exchgesel, method_getImplementation(originalM), method_getTypeEncoding(originalM));
}
else
{
method_exchangeImplementations(originalM, exchangeM);
}
}
- (void)ly_setBackGroundColor:(UIColor *)color
{
[self ly_setBackGroundColor:[UIColor cyanColor]];
}
至于具体原理可去搜索runtime机制
网友评论