KVC的一些用法


1.KVC之字典转模型

- (instancetype)initWithDict:(NSDictionary *)dict

{

    self = [super init];

    if (self) {

//        self.answer = dict[@"answer"];

//        self.icon = dict[@"icon"];

//        self.title = dict[@"title"];

//        self.options = dict[@"options"];

        

        //KVC (key value coding)键值编码

        //cocoa 的大招,允许间接修改对象的属性值

        //第一个参数是字典的属性

        //第二个参数是类的属性

//        [self setValue:dict[@"answer"] forKeyPath:@"answer"];

//        [self setValue:dict[@"icon"] forKeyPath:@"icon"];

//        [self setValue:dict[@"title"] forKeyPath:@"title"];

//        [self setValue:dict[@"options"] forKeyPath:@"options"];

        //使用setValuesForKeys要求类的属性必须在字典中存在

        [self setValuesForKeysWithDictionary:dict];

    return self;

}


+ (instancetype)questionWithDict:(NSDictionary *)dict

{

    return [[self alloc] initWithDict:dict];

}

2.    使用KVC间接修改对象属性时,系统会自动判断对象属性的类型,并完成转换

    Person *p1 = [[Person alloc] init];

    [p1 setValue:@"mike" forKeyPath:@"name"];

    // NSNumber 基本数据类型

    // NSValue 结构体

    [p1 setValue:@"18" forKeyPath:@"age"];

3 .KVC按照键值路径取值时,如果对象不包含指定的键值,会自动进入对象内部,查找对象属性

列如:p1是含有name的对象,persons是拥有子元素p1和p2的数组

[p1 valueForKeyPath:@"name"] //取p1中name的值

NSArray *array = [persons valueForKeyPath:@"name"];//取p1和p2的内部属性的值,并组成数组


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值