通过NSDictionary迭代null值

kfo*_*rim 1 iphone cocoa objective-c ipad ios

我有一些带有几把钥匙的NSDictionary,但是他们在雇佣部门的部门很多,例如:

  1. 人:
    • 性别:
      • 名称:
        • 地址:
  2. 地点:

所以你可以看看我是否在nsdictionary中插入它,最初我只有两个键作为"Person"和"Location",但是我试图在每个键中迭代以检查空值并将其设置为@""空字符串.

有谁知道如何迭代这样的部门?

谢谢

bbu*_*bum 6

  • 你不能存储nilNSDictionary.要么你正在寻找,[NSNull null]要么你会找到缺少你正在寻找的键的词典....

  • enumerateKeysAndObjectsUsingBlock:比...更快for( ... in ...).

  • 如果要修改字典的内容,则必须使用可变字典.如果从属性列表中取消归档,则可以选择使用不可变节点创建可变容器(这可能是您想要的).

Recurse是答案,尽管没有显示递归的答案是正确的.

- (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 ...
            }
      }];
}
Run Code Online (Sandbox Code Playgroud)


jbc*_*man 5

最简单的形式:

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    if ([obj isKindOfClass:[NSNull class]]) [dictionary setValue:[NSString stringWithString:@""] forKey:key];
} ];
Run Code Online (Sandbox Code Playgroud)