使用字典值动态填充对象属性
在 Objective-C 中,我有一个字典:
firstName -> John
lastName -> Smith
age -> 34
和一个具有相应实例变量和属性(适当处理内存管理)的对象 Person
。我想创建一个方便的初始化程序,它采用字典作为参数,并从字典键/值填充所有对象字段(通过其属性用于内存管理目的),而不是手动执行以下操作:
obj.firstName = [dict objectForKey:@"firstName"];
obj.lastName = [dict objectForKey:@"lastName"];
obj.age = [dict objectForKey:@"age"];
....
我该怎么做?
In Objective-C, I have a dictionary:
firstName -> John
lastName -> Smith
age -> 34
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"];
....
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用键值编码:
另请参阅
-setValuesForKeysWithDictionary:
的文档。You can use Key-Value Coding:
See also the documentation for
-setValuesForKeysWithDictionary:
.