这个问题类似于
this question,但是这种方法只适用于字典的根级别.
我正在用空字符串替换任何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值,包括嵌套字典??
解决方法
该方法的一个小修改可以使其递归:
@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 self) { const id object = [self objectForKey: key]; if (object == nul) { [replaced setObject: blank forKey: key]; } else if ([object isKindOfClass: [NSDictionary class]]) { [replaced setObject: [(NSDictionary *) object dictionaryByReplacingNullsWithStrings] forKey: key]; } } return [NSDictionary dictionaryWithDictionary: replaced]; }
请注意,快速枚举现在是自己,而不是替换
上面的代码,这个例子:
NSMutableDictionary *dic1 = [NSMutableDictionary dictionary]; [dic1 setObject: @"string 1" forKey: @"key1.1"]; [dic1 setObject: [NSNull null] forKey: @"key1.2"]; NSMutableDictionary *dic2 = [NSMutableDictionary dictionary]; [dic2 setObject: @"string 2" forKey: @"key2.1"]; [dic2 setObject: [NSNull null] forKey: @"key2.2"]; [dic1 setObject: dic2 forKey: @"key1.3"]; NSLog(@"%@",dic1); NSLog(@"%@",[dic1 dictionaryByReplacingNullsWithStrings]);
呈现此结果:
2012-09-01 08:30:16.210 Test[57731:c07] { "key1.1" = "string 1"; "key1.2" = "<null>"; "key1.3" = { "key2.1" = "string 2"; "key2.2" = "<null>"; }; } 2012-09-01 08:30:16.212 Test[57731:c07] { "key1.1" = "string 1"; "key1.2" = ""; "key1.3" = { "key2.1" = "string 2"; "key2.2" = ""; };