用字典值动态填充对象属性 [英] Dynamically populate object properties with dictionary values

查看:159
本文介绍了用字典值动态填充对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我有一个字典:

In Objective-C, I have a dictionary:

firstName -> John
lastName -> Smith
age -> 34

和一个对象 Person 实例变量和属性(适当地处理内存管理)。我想创建一个方便的初始化器,它将字典作为参数,并从字典键/值中填充所有对象字段(通过其用于内存管理的属性),而不是手动执行以下操作:

and an object Person that has corresponding instance variables and properties (that handle memory management appropriately). I'd like to create a convenience initializer that takes a dictionary as an argument and populates all the object fields (via their properties for memory management purposes) from the dictionary keys/values, instead of manually doing something like:

obj.firstName = [dict objectForKey:@"firstName"];
obj.lastName = [dict objectForKey:@"lastName"];
obj.age = [dict objectForKey:@"age"];
....

我该怎么做?

推荐答案

您可以使用键值编码

[obj setValuesForKeysWithDictionary:dict];

另请参见 -setValuesForKeysWithDictionary: / code>

这篇关于用字典值动态填充对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆