这个问题类似于这个问题,但是这种方法只适用于字典的根级别。
我正在寻找NSNull
用空字符串替换任何出现的值,以便我可以将完整的字典保存到 plist 文件中(如果我将它与 NSNull 一起添加,则文件不会写入)。
然而,我的字典里面有嵌套的字典。像这样:
"dictKeyName" = {
innerStrKeyName = "This is a string in a dictionary";
innerNullKeyName = "<null>";
innerDictKeyName = {
"innerDictStrKeyName" = "This is a string in a Dictionary in another Dictionary";
"innerDictNullKeyName" = "<null>";
};
};
如果我使用:
@interface NSDictionary (JRAdditions)
- (NSDictionary *) dictionaryByReplacingNullsWithStrings;
@end
@implementation NSDictionary (JRAdditions)
- (NSDictionary *) dictionaryByReplacingNullsWithStrings {
const NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary:self];
const id nul = [NSNull null];
const NSString *blank = @"";
for(NSString *key in replaced) {
const id object = [self objectForKey:key];
if(object == nul) {
[replaced setObject:blank forKey:key];
}
}
return [NSDictionary dictionaryWithDictionary:replaced];
}
@end
我得到这样的东西:
"dictKeyName" = {
innerStrKeyName = "This is a string in a dictionary";
innerNullKeyName = ""; <-- this value has changed
innerDictKeyName = {
"innerDictStrKeyName" = "This is a string in a Dictionary in another Dictionary";
"innerDictNullKeyName" = "<null>"; <-- this value hasn't changed
};
};
有没有办法NSNull
从包括嵌套字典在内的所有字典中找到每个值......?
编辑: 数据是从 JSON 提要中提取的,因此我收到的数据是动态的(我不想在每次提要更改时都更新应用程序)。