在 Objective-C 中从 NSDictionary 创建 NSObject

发布于 2025-01-07 00:52:15 字数 389 浏览 0 评论 0原文

我想使用“for...in”循环将字典中的每个项目分配到我的对象中

我有一个这样的 NSDictionary :

{"user_id" : "1", "user_name" : "John"}

并且我有一个带有变量的 NSObject :

NSString *user_id;
NSString *user_name

使用 for in 循环,我想分配每个项目从我的 NSObject 中的 NSDictionary

for (NSString *param in userDictionary) {

}

我该怎么做?

谢谢,

I would like to assign each item from a dictionary into my object using a "for...in" loop

I have a NSDictionary like that :

{"user_id" : "1", "user_name" : "John"}

And I have an NSObject with variable :

NSString *user_id;
NSString *user_name

With a for in loop, I want to assign each item from my NSDictionary in my NSObject

for (NSString *param in userDictionary) {

}

How I can do that ?

Thanks,

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

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

发布评论

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

评论(2

如梦初醒的夏天 2025-01-14 00:52:15

看一下 NSObject 类方法:

- (void)setValue:(id)value forKey:(NSString *)key;

例如:

[userDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
    [myObject setValue:obj forKey:(NSString *)key];
}];

Have a look at the NSObject class method:

- (void)setValue:(id)value forKey:(NSString *)key;

For example:

[userDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
    [myObject setValue:obj forKey:(NSString *)key];
}];
秋日私语 2025-01-14 00:52:15

我编写了一个小型库来自动执行此操作,它还处理日期转换
https://github.com/aryaxt/OCMapper

只要所有键都在,它就会自动将 NSDictionary 转换为 NSObject与属性名称相同。

Customer *customer = [Customer objectFromDictionary:customerDictionary];
NSArray *customers = [Customer objectFromDictionary:listOfCustomersDictionary];

如果键和属性名称不同,您可以编写映射

[mappingProvider mapFromDictionaryKey:@"dob" toPropertyKey:@"dateOfBearth" forClass:[Customer class]];

I wrote a small library that automates this, it also handles conversion of dates
https://github.com/aryaxt/OCMapper

It automatically converts NSDictionary to NSObject as long as all keys are the same as property names.

Customer *customer = [Customer objectFromDictionary:customerDictionary];
NSArray *customers = [Customer objectFromDictionary:listOfCustomersDictionary];

if the key and property names are not the same you can write mapping

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