views:

104

answers:

3

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)
A: 

ok unless I'm missing something why not create a method like:

setObjectProperties: (id) Object withValues:(NSDictionary *)dict

ennuikiller
Sorry, my question wasn't clear enough. I have clarified it.
Gerald Kaszuba
A: 

I've never done this, but this seems like it should work:

For each key in the dictonary:

NSString* setMethod = "set" + [key capitalizedString] + ":";  // This is pseudo-code.
SEL setSelector = NSSelectorFromString(setMethod);
[objectInstance performSelector:setSelector withObject:[dict objectForKey:key]];

(The code to form setMethod is pseudo-code & left as an exercise because Obj-C string manipulation is horrible.)

Grumdrig
This is just reinventing the KVC wheel.
Chuck
It certainly is! I recommend voting for the accepted answer (which was news to me).
Grumdrig
+7  A: 

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

Chuck