我经常发现需要缓存由NSJSONSerialization磁盘创建的数据结构,-writeToFile如果有空值则失败,我需要一个在结构未知时有效的修复.这是有效的,并且允许直接变异,因为NSMutableDictionary本身的实例没有被枚举,但感觉有点hacky.
这是完全正常还是重新创建一棵新树并返回它是绝对必要的?
- (void) removeNullsFromJSONTree:(id) branch
{
if ([branch isKindOfClass:[NSMutableArray class]])
{
//Keep drilling to find the leaf dictionaries
for (id childBranch in branch)
{
[self removeNullsFromJSONTree:childBranch];
}
}
else if ([branch isKindOfClass:[NSMutableDictionary class]])
{
const id nul = [NSNull null];
const NSString *empty = @"";
for(NSString *key in [branch allKeys])
{
const id object = [branch objectForKey:key];
if(object == nul)
{
[branch setObject:empty forKey:key];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)