1

我有一个包含以下内容的 plist 文件:

<plist>
 <dict>
  <key>Rows</key>
   <array>
        <dict>
            <key>Asia</key>
            <string>India</string>
            <array>
                 <dict>
                      <key>Description</key>
                      <string>Country</string>
                 </dict>
            </array>
        </dict>
        <dict>
            <key>Europe</key>
            <string>Germany</string>
            <array>
                 <dict>
                      <key>Germany</key>
                      <string>Berlin</string>
                      <array>
                           <dict>
                                <key>Description</key>
                                <string>State</string>
                           </dict>
                      </array>
                 </dict>
            </array>
        </dict>
   </array>

我将此内容存储在 NSDictionary 中。从这里有什么方法可以让我只获得关键是 "description" 的那些对象。我找不到任何解决方案,因为键“描述”没有固定位置,这意味着 plist 中可以有任意数量的子级别。但是这个键将永远是最后一个子级别。

4

1 回答 1

1

您需要通过字典进行递归,并获取每个具有描述键的列表。像这样的东西(未经测试):

NSDictionary *rootLevel = //dictionary from plist
NSArray *dictionariesWithKey = [self dictionariesWithDescriptionKeyFromDictionary:rootLevel];


- (NSArray *)dictionariesWithDescriptionKeyFromDictionary:(NSDictionary *)dict
{
    NSMutableArray *dictionaries = [NSMutableArray array];
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id val, BOOL *stop) {

        if ([key isEqualToString:@"description"])
            [dictionaries addObject:dict];
        else if ([val isKindOfClass:[NSDictionary class]])
            [dictionaries addObjectsFromArray:[self dictionariesWithDescriptionKeyFromDictionary:val]];
    }];
    return dictionaries;
}
于 2013-03-19T07:45:02.110 回答