Runtime-ios的黑魔法,还是很好玩的,消息机制、方法替换简单记录了一点,持续更新....
1.方法替换
在类load方法中,替换系统方法
+ (void)load{ Method oldColorMethod = class_getInstanceMethod([self class], @selector(setBackgroundColor:)); Method newColorMethod = class_getInstanceMethod([self class], @selector(xg_setBackgroundColor:)); ///交换方法 ///调用系统的setBackgroundColor方法就会执行xg_setBackgroundColor方法 method_exchangeImplementations(oldColorMethod, newColorMethod); } - (void)xg_setBackgroundColor:(UIColor *)color{ ///在此方法中不要调用系统的setBackgroundColor方法,防止循环引用 [self xg_setBackgroundColor:color]; }
2.动态生成属性
- (void)setNamexg:(NSString *)namexg{ objc_setAssociatedObject(self, "namexg", namexg, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSString *)namexg{ return objc_getAssociatedObject(self, "namexg"); }
3.字典转模型的实现
#import "NSObject+xgDictionary.h" #import <objc/runtime.h> @implementation NSObject (xgDictionary) + (instancetype)xg_modelKeyValues:(NSDictionary *)dicData{ id model = [[self alloc]init]; unsigned int count = 0; ///返回类的所有属性和变量 Ivar *ivarsA = class_copyIvarList(self, &count); for (int i = 0; i < count; i ++) { Ivar iv = ivarsA[i]; NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(iv)]; ivarName = [ivarName substringFromIndex:1]; id value = dicData[ivarName]; [model setValue:value forKeyPath:ivarName]; } return model; } @end