1、使用KVC,新建一个 USer 类
#import "User.h"
@interface User()
{
NSString *_name;
}
@property (nonatomic, copy) NSString *type;
@end
@implementation User
- (instancetype)init
{
self = [super init];
if (self) {
_name = @"initName";
self.type = @"initType";
}
return self;
}
- (void)before
{
NSLog(@"修改之前:%@ -- %@",_name,self.type);
}
- (void)after
{
NSLog(@"修改之后:%@ -- %@",_name,self.type);
}
修改
User *u1 = [[User alloc] init];
[u1 before];
[u1 setValue:@"chen" forKey:@"name"];
[u1 after];
打印结果:
修改之前:initName -- initType
修改之后:chen -- initType
访问的可以使用方法
NSString *name = [u1 valueForKeyPath:@"type"];
NSString *type = [u1 valueForKey:@"name"];
2、使用runtime
User *u1 = [[User alloc] init];
[u1 before];
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList([u1 class], &count);
for (int i=0; i<count; i++)
{
Ivar ivar = ivarList[i];
const char *privateName = ivar_getName(ivar);
NSLog(@"%s",privateName);
}
Ivar name = ivarList[0];
Ivar type = ivarList[1];
// 访问
NSLog(@"%@ -- %@",object_getIvar(u1, name),object_getIvar(u1, type));
object_setIvar(u1, name, @"newName");
object_setIvar(u1, type, @"newType");
[u1 after];
打印结果
修改之前:initName -- initType
_name
_type
initName -- initType
修改之后:newName -- newType
修改和访问成功
网友评论