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

北战南征 提交于 2020-01-23 12:50:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!