Neha Dangui
Neha Dangui

Reputation: 647

Copy contents of one NSDictionary into another NSDictionary

I have a plist file having the following content:

<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>

I am storing this content in a NSDictionary . From this is there any way how I can get only those objects where key is "description" . I could not find any solution as there is no fixed position of the key "description" meaning there can be any number of sub levels in the plist . But this key will always be the last sub level.

Upvotes: 1

Views: 918

Answers (1)

wattson12
wattson12

Reputation: 11174

You need to recurse through the dictionaries, and get a list of each one which has a key of description. Something like this (not tested):

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;
}

Upvotes: 1

Related Questions