有没有办法创建条件 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 usingremoveObjectForKey:
.
因此,请使用 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/