Runtime
https://www.jianshu.com/p/6ebda3cd8052
开发中可能用到的Runtime:在Category中添加属性, 交换方法的实现,归档接档(获取所用的变量, 属性, 方法名, 协议名),动态添加方法
1:添加属性
objc_setAssociatedObject(self, _cmd, girlFriend, OBJC_ASSOCIATION_RETAIN);
objc_getAssociatedObject(self, @selector(setGirlFriend:));
2:方法交换
+ (void)MethodSwapWithSEL:(SEL)sel1 otherSEL:(SEL)sel2 { Method fromMethod = class_getInstanceMethod([self class], sel1); Method toMethod = class_getInstanceMethod([self class], sel2); method_exchangeImplementations(fromMethod, toMethod); }
3:获取所有的变量,属性,方法, 协议名
/// 变量 unsigned int count = 0; Ivar *ivarList = class_copyIvarList([People class], &count); for (int i = 0; i < count; i++) { // 变量的名 NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivarList[i])]; // 变量的类型 NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivarList[i])]; }
unsigned int count = 0; /// 属性 objc_property_t *propertyList = class_copyPropertyList([People class], &count); /// 方法 Method *methodList = class_copyMethodList([People class], &count); /// 协议 class_copyProtocolList([People class], &count);
4 动态添加方法
+ (BOOL)resolveClassMethod:(SEL)sel { } + (BOOL)resolveInstanceMethod:(SEL)sel { }
重定向
- (id)forwardingTargetForSelector:(SEL)aSelector { }
转发
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { } - (void)forwardInvocation:(NSInvocation *)anInvocation { }