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"];
object开发者_如何学CInstace.val2 = [dict objectForKey:@"val2"];
with something like this (pseudo code):
for key, value in dict:
setattr(objectInstance, key, value)
You can use the Key-Value Coding method setValuesForKeysWithDictionary:
. It does precisely what you want. Just [someObject setValuesForKeysWithDictionary:propertiesDictionary]
.
ok unless I'm missing something why not create a method like:
setObjectProperties: (id) Object withValues:(NSDictionary *)dict
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.)
精彩评论