问题
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)
回答1:
You can use the Key-Value Coding method setValuesForKeysWithDictionary:. It does precisely what you want. Just [someObject setValuesForKeysWithDictionary:propertiesDictionary]
.
回答2:
ok unless I'm missing something why not create a method like:
setObjectProperties: (id) Object withValues:(NSDictionary *)dict
回答3:
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.)
来源:https://stackoverflow.com/questions/1760689/automatically-populate-all-properties-of-an-objective-c-instance-with-a-dictiona