iOS runtime和kvc的相同运用 访问对象的私有属性
2020-04-08 本文已影响0人
神奇李白
Person.h
@property (strong , nonatomic) NSString *name;
Person.m
@property (strong , nonatomic) NSString *age;
怎样需要访问Person类中的私有属性age?
方法1 通过KVC访问
Person *p = [[Person alloc]init];
//赋值
[p setValue:@"26" forKeyPath:@"_age"];
//取值
NSString *age = [p valueForKeyPath:@"_age"];
NSLog(@"age = %@",age);
方法2 通过runtime访问
Person *p = [[Person alloc]init];
//获取对象的私有属性
Ivar ivarName = class_getInstanceVariable([p class], "_age");
NSLog(@"属性名:%s",ivar_getName(ivarName));
//给成员变量赋值
object_setIvar(p, ivarName, @"52");
NSLog(@"age = %@",object_getIvar(p, ivarName));