ios - 是否有创建条件 NSDictionary 的简写语法?

标签 ios objective-c nsdictionary

有没有办法创建条件 NSDictionary?例如,假设有一个具有 3 个属性的自定义类:

class UserInfoObject
   firstName
   lastName
   address

我需要的是为 userInfoObject 中的非零属性创建 NSDictionary。当我提前知道哪些属性非零时,这很简单,因此我可以使用这种简写语法(或经典语法):

NSDictionary *userInfoDic = @{@"firstName": userInfoObject.firstName, @"lastName":userInfoObject.lastName, @"address":userInfoObject.address}

但是就我而言,我需要创建可变字典,然后对每个属性执行手动检查/添加。下面还有另一种更短的方法吗?

// Create mutable thing
NSMutableDictionary *userInfoDic = [NSMutableDictionary new];

// Check and add first name
if (userInfoDic.firstName) {
   userInfoDic[@"firstName"] = userInfoDic.firstName;
}

// Check and add last name 
if (userInfoDic.lastName) {
   userInfoDic[@"lastName"] = userInfoDic.lastName;
}

// Check and add address
if (userInfoDic.address) {
   userInfoDic[@"address"] = userInfoDic.address;
}

我有很多类和属性,所以速记(如果存在)可以促进这个过程:)

最佳答案

NSMutableDictionary already does this

setValue:forKey: 对可变字典执行此操作:

This method adds value and key to the dictionary using setObject:forKey:, unless value is nil in which case the method instead attempts to remove key using removeObjectForKey:.

因此,请使用 setValue:forKey: 而不是 setObject:forKey:。此方法没有速记文字。您可以编写自己的 NSMutableDictionary 子类并重写 setObject:forKeyedSubscript: 来安全地忽略 nil 对象,但这似乎需要太多工作。正如文件所说:

There should typically be little need to subclass NSMutableDictionary. If you do need to customize behavior, it is often better to consider composition rather than subclassing.

这意味着您应该而不是子类化,创建自己的包装对象,该对象具有 NSMutableDictionary 作为后备存储,并实现访问内部字典所需的所有方法,覆盖 setObject:forKeyedSubscript: 与 nil 一起使用。但我不会仅仅为了避免在其他地方编写几行代码而推荐它。

关于ios - 是否有创建条件 NSDictionary 的简写语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20702344/

相关文章:

iphone - 使用 block 将NSDictionary转换为字符串?

ios - 映射到 Realm 结果到 NSDictionary 错误

arrays - 在 Swift 中访问 NSDictionary 中的数据

android - 尝试使用 ButtonTheme 设置最小宽度时出错

objective-c - XCode 构建结果 : why is it so amazingly complex even for a hello world console app?

objective-c - Objective-C 中的 `add target` 和 `implements a delegate` 有什么区别?

iphone - 在运行时浏览核心数据内容(通过 Xcode 模拟器)

objective-c - 如何获得当前一周的天数?

iphone - 应用程序崩溃使用 popViewController 动画 :YES

ios - Spotify iOS SDK - 无后台播放