runtime的用法
2018-07-10 本文已影响11人
Jorunk
- 1.使用runtime改变变量值
//成员变量个数
unsigned int count = 0;
//获取所引用的实例变量
Ivar *ivars = class_copyIvarList([Preson class], &count);
//遍历
for (int i = 0; i < count; i++) {
//取出第i位置成员变量
Ivar ivar = ivars[i];
//查看成员变量
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
if ([key isEqualToString:@"_name"]) {
object_setIvar(self.person, ivar, @"name1");
break;
}
- 2.使用runtime交换方法
//获取方法
Method m1 = class_getInstanceMethod([self.person class], @selector(firstMethod));
Method m2 = class_getInstanceMethod([self.person class], @selector(secondMethod));
method_exchangeImplementations(m1, m2);
}
- 3.使用runtime添加方法
//"v@:@" v表示void,@表示id,:表示SEL
class_addMethod([self.person class], @selector(run:), (IMP)runMethod, "v@:@")
- 4.使用runtime给分类扩展属性
- (void)setNick:(NSString *)nick
{
objc_setAssociatedObject(self, &name, nick, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)nick
{
return objc_getAssociatedObject(self, &name);
}