iOS:class_copyPropertyList 与 class_copyIvarList 区别

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_copyPropertyListclass_copyIvarList 实现字典转模型的功能的第三方有:YYModel、MJExtension、JSONModel等。

其中 YYModel、MJExtension 使用的是 class_copyIvarList
JSONModel 使用的是 class_copyPropertyList

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值