开发者

Dynamically populate object properties with dictionary values

开发者 https://www.devze.com 2023-03-12 00:39 出处:网络
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 managem

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 dic开发者_StackOverflowtionary 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?


You can use Key-Value Coding:

[obj setValuesForKeysWithDictionary:dict];

See also the documentation for -setValuesForKeysWithDictionary:.

0

精彩评论

暂无评论...
验证码 换一张
取 消