class_copyPropertyList
返回的仅仅是对象类的属性( @property 申明的属性),而 class_copyIvarList
返回类的所有属性和变量(包括在 @interface 大括号中声明的变量),下面做个简单的测试。首先,定义一个 Man 类 :
@interface Man : NSObject
{
NSString *IDCard;
NSString *birthday;
NSString *hobby;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *user_id;
@property (nonatomic, copy) NSString *address;
- (void)class_copyPropertyListAndclass_copyIvarList;
@end
然后在测试类中写一个测试函数 class_copyPropertyListAndclass_copyIvarList
调用上述两个函数得到其返回结果再分别依次遍历输出其返回值。
- (void)class_copyPropertyListAndclass_copyIvarList{
id classObject = objc_getClass([@"Man" UTF8String]);
unsigned int count = 0;
unsigned int icount = 0;
// 获取属性列表
objc_property_t *properties = class_copyPropertyList(classObject, &count);
// 获取成员变量列表
Ivar *ivars = class_copyIvarList(classObject, &icount);
NSLog(@"Count:%d,ICount:%d",count,icount);
for (int i = 0; i < count; i++) {
objc_property_t property = properties[i];
// 获取属性名称
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
NSLog(@"propertyName:%@",propertyName);
}
for (int i = 0; i < icount; i++) {
NSString *memberName = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
NSLog(@"ivarName:%@",memberName);
}
}
执行上述测试函数后在控制台输出结果为:
从上述执行结果可以很好的说明前者只获取由 @property 声明的属性,而后者不但获取了 @property 属性,而且还获取了 @interface 大括号中声明的变量。
补充
使用 class_copyPropertyList
与 class_copyIvarList
实现字典转模型的功能的第三方有:YYModel、MJExtension、JSONModel等。
其中 YYModel、MJExtension 使用的是 class_copyIvarList
。
JSONModel 使用的是 class_copyPropertyList
。