I have a large NSDictionary
that I need to loop through and create separate NSArray
s. Here are the contents:
(
{
id =
Modern Objective-C syntax:
NSMutableArray *things = [NSMutableArray array];
NSMutableArray *stuff = [NSMutableArray array];
NSMutableArray *bits = [NSMutableArray array];
[dictionaries enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[things addObject:[obj valueForKeyPath:@"thing"]];
[stuff addObject:[obj valueForKeyPath:@"enclosing_object.stuff"]];
[bits addObject:[obj valueForKeyPath:@"bits"]];
}];
NSString *key;
for(key in someDictionary){
NSLog(@"Key: %@, Value %@", key, [someDictionary objectForKey: key]);
}
It's somewhat unclear by your log, but I'm guessing your NSDictionary
has values of NSDictionary
? If so:
NSMutableArray *titles = [NSMutableArray array];
// etc.
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
if ([subDictionary objectForKey:@"type"] == @"title")
[titles addObject:[subDictionary objectForKey:@"title"]];
// etc.
}
Your question is a bit unclear... but this is how you would properly loop through an NSDictionary
.
EDIT:
NSMutableDictionary *galleries = [NSMutableDictionary dictionary];
NSString *currentTitle;
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
NSString *type = [subDictionary objectForKey:@"type"];
if (type == @"title") {
currentTitle = [subDictionary objectForKey:@"title"];
if ([galleries objectForKey:currentTitle] == nil)
[galleries setObject:[NSMutableArray array] forKey:currentTitle];
} else if (type == @"gallery" && currentTitle != nil)
[[galleries objectForKey:currentTitle] addObject:subDictionary];
}
After this loop, galleries
will contain keys of type NSString
(with values of the titles), and corresponding objects of type NSArray
(with values of the gallery NSDictionarys
). Hopefully this is what you were going for.