【问题标题】:Set the properties of an NSObject from the values in an NSDictionary从 NSDictionary 中的值设置 NSObject 的属性
【发布时间】:2013-07-26 16:42:31
【问题描述】:

我想知道是否可以从NSDictionary 设置NSObject 的属性,而无需单独设置每个属性。

NSObject 中的属性名称与 NSDictionary 中的键名称匹配。

有没有一种简单的方法可以做到这一点?

【问题讨论】:

标签: cocoa-touch nsdictionary declared-property


【解决方案1】:

假设值的类型匹配,您想使用- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues NSNull 值将被视为 nil。

【讨论】:

  • 这是假设您在字典中存储了正确的类型。
  • 没错,我会记下来的。
【解决方案2】:

我编写了一个小型库来自动执行此操作,它还处理日期转换 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]];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多