Search code examples
objective-cintrospection

Automatically populate all properties of an Objective C instance with a dictionary


I have a class with properties that I would like to set values from a dictionary.

In other words, I would like to automate this:

objectInstace.val1 = [dict objectForKey:@"val1"];
objectInstace.val2 = [dict objectForKey:@"val2"];

with something like this (pseudo code):

for key, value in dict:
    setattr(objectInstance, key, value)

Solution

  • You can use the Key-Value Coding method setValuesForKeysWithDictionary:. It does precisely what you want. Just [someObject setValuesForKeysWithDictionary:propertiesDictionary].