今天闲来无事,突然想到使用runtime获取类中的私有成员,然后进行KVC赋值. (其实这种小方法,在一年之前就看到过, 只不过当时还不怎么明白,算是窃取别人的成果了)
首先创建一个People类,在.m中创建私有成员变量.
#import "People.h"
@interface People()
{
NSString *name;
}
@property (nonatomic, copy)NSString *age;
@end
@implementation People
@end
然后在viewController中通过runtime获取私有变量(虽然咱自己知道私有成员变量名字是什么,这里假设不知道私有成员变量的名字)
#pragma mark ----使用runtime获取成员变量列表
unsigned int count;
Ivar *peopleList = class_copyIvarList([People class], &count);
for (unsigned int i = 0; i < count; i++)
{
Ivar peopleIvar = peopleList[i];
const char *ivarName = ivar_getName(peopleIvar);
NSLog(@"peopleIvarName == %@",[NSString stringWithUTF8String:ivarName]);
}
通过打印知道私有变量名字,然后就可以通过KVC赋值了(其实在项目中,我几乎就没用到过KVC进行赋值)
#pragma mark ----使用KVC进行赋值
[peopleObject setValue:@"23" forKey:@"age"];
NSString *peopleAge = [peopleObject valueForKey:@"age"];
NSLog(@"peopleName == %@", peopleAge);
[peopleObject setValue:@"吴晓群" forKey:@"name"];
NSString *peopleName = [peopleObject valueForKey:@"name"];
NSLog(@"peopleName == %@", peopleName);
OK了,这样就可以给类中私有成员变量赋值了