Runtime
Posted jisa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 { }
以上是关于Runtime的主要内容,如果未能解决你的问题,请参考以下文章
为啥在 Zapier 中使用此代码时会出现 Runtime.MarshalError?