我有一个特定的NSDictionary,其中有几个键但它们在层次结构中更深入,例如:
- 人:
- 性别:
- 名称:
- 地址:
- 名称:
- 性别:
- 位置:
所以你可以看到如果我在nsdictionary中插入这个,最初我只有两个键作为"Person"one_answers"Location",但是我试图在每个键中迭代以检查空值并将其设置为@"空字符串。
有人知道如何遍历这样的深度吗?
谢谢
-
你不能在
NSDictionary
中存储nil
。要么你要找[NSNull null]
要么你要找的字典缺少你要找的键.... -
enumerateKeysAndObjectsUsingBlock:
比for( ... in ...)
更快。 -
如果要修改字典的内容,则必须使用可变字典。如果要从属性列表中解归档,可以使用不可变节点创建可变容器(这可能是您想要的)。
递归是答案,尽管没有一个显示递归的答案是正确的。
- (void)filterMutableDictionary:(NSMutableDictionary*)aDictionary
{
// check if aDictionary is missing any keys here
if (![aDictionary objectForKey:@"DesiredKey"]) {
... fill in key/value here ...
}
// enumerate key/values, filtering appropriately, recursing as necessary
[aDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
if ([value isKindOfClass: [NSMutableDictionary class]]) {
[self filterMutableDictionary: value];
} else {
... filter value here ...
}
}];
}
最简单的形式:
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSNull class]]) [dictionary setValue:[NSString stringWithString:@""] forKey:key];
} ];
您可以使用递归方法,像这样:
- (void)recursive:(NSDictionary*)aDictionary {
for (id key in aDictionary) {
id value = [aDictionary objectForKey:key];
if ([value isKindOfClass:[NSDictionary class]]) {
[self recursive:value];
} else {
// Do something else, the value is not a dictionary
}
}
}
当你在循环中检查值时,使用这个来检查null
if ([[dict objectForKey:@"Gender"] isKindOfClass:[NSNull class]]) {
// null value
myGender = @"";
}
- (void)recursive:(NSDictionary)dictionary {
for (NSString *key in [dictionary allKeys]) {
id nullString = [dictionary objectForKey:key];
if ([nullString isKindOfClass:[NSDictionary class]]) {
[self recursive:(NSDictionary*)nullString];
} else {
if ( (NSString*)nullString == nil)
[dictionary setObject:@"" forKey:@"key"];
}
}
}