Dynamically populate object properties with dictionary values

别说谁变了你拦得住时间么 提交于 2019-12-21 05:03:37

问题


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?


回答1:


You can use Key-Value Coding:

[obj setValuesForKeysWithDictionary:dict];

See also the documentation for -setValuesForKeysWithDictionary:.



来源:https://stackoverflow.com/questions/6299007/dynamically-populate-object-properties-with-dictionary-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!