Runtime-iOS的黑魔法,還是很好玩的,消息機制、方法替換簡單記錄了一點,持續更新.... 1.方法替換 在類load方法中,替換系統方法 2.動態生成屬性 3.字典轉模型的實現 ...
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