使用字典自动填充 Objective C 实例的所有属性

发布于 2024-08-11 22:55:19 字数 289 浏览 2 评论 0原文

我有一个类,其中包含我想从字典中设置值的属性。

换句话说,我想自动化这个:

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

用这样的东西(伪代码):

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

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独陪着我 2024-08-18 22:55:19

您可以使用键值编码方法 setValuesForKeysWithDictionary:。它正是您想要的。只需[someObject setValuesForKeysWithDictionary:propertiesDictionary]

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

深府石板幽径 2024-08-18 22:55:19

好吧,除非我错过了一些东西,为什么不创建一个像这样的方法:

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

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

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

雪花飘飘的天空 2024-08-18 22:55:19

我从来没有这样做过,但这似乎应该有效:

对于字典中的每个key:(

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

形成setMethod的代码是伪代码&左为一个练习,因为 Obj-C 字符串操作很糟糕。)

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文