正文
接下来我们就来看看NSObject+Runtime中的内容,其对Runtime常用的方法进行了简单的封装:
别着急,我们一个一个看。
1、获取成员变量
下面这个方法就是获取类的成员变量列表,其中包括属性生成的成员变量。我们可以用ivar_getTypeEncoding()来获取成员变量的类型,用ivar_getName()来获取成员变量的名称:
+ (NSArray *)fetchIvarList
{
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList(self, &count);
NSMutableArray *mutableList = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i = 0; i < count; i++ )
{
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
const char *ivarName = ivar_getName(ivarList[i]);
const char *ivarType = ivar_getTypeEncoding(ivarList[i]);
dic[@"type"] = [NSString stringWithUTF8String: ivarType];
dic[@"ivarName"] = [NSString stringWithUTF8String: ivarName];
[mutableList addObject:dic];
}
free(ivarList);
return [NSArray arrayWithArray:mutableList];
}
使用[TestClass fetchIvarList]方法获取TestClass类的成员变量结果:
TestClass的成员变量列表
2、获取属性列表
下面这个方法获取的是属性列表,包括私有和公有属性,也包括分类中的属性:
+ (NSArray *)fetchPropertyList
{
unsigned int count = 0;
objc_property_t *propertyList = class_copyPropertyList(self, &count);
NSMutableArray *mutableList = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i = 0; i < count; i++)
{
const char *propertyName = property_getName(propertyList[i]);
[mutableList addObject:[NSString stringWithUTF8String:propertyName]];