5

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?

jrdioko
  • 32,230
  • 28
  • 81
  • 120

1 Answers1

20

You can use Key-Value Coding:

[obj setValuesForKeysWithDictionary:dict];

See also the documentation for -setValuesForKeysWithDictionary:.

John Calsbeek
  • 35,947
  • 7
  • 94
  • 101
  • Is there a similar method to go the other way (convert object to dictionary)? – ebi Aug 20 '13 at 19:49
  • @ebi `-dictionaryWithValuesForKeys:`, whose documentation is on the same page. – John Calsbeek Aug 20 '13 at 23:34
  • If I'm not mistaken you need to declare the keys - I'm looking for a simpler way.. – ebi Aug 21 '13 at 03:19
  • @ebi The runtime has no idea what selectors on your object correspond to keys. If a method to get all the properties on your object existed, it would have to call every method that has the right signature. Is `- (MyObject *)newObject` a method which creates a new object, or a method which returns the value of the `newObject` property? – John Calsbeek Aug 21 '13 at 04:20
  • A new instance of the object? – ebi Aug 21 '13 at 06:28
  • 1
    @ebi I'm asking hypothetically, because it has the same signature as any property, so a hypothetical "dictionary of all properties" would need to call that method (and any similar one), despite having no idea whether it is actually a property. – John Calsbeek Aug 21 '13 at 14:34