Loop through NSDictionary to create separate NSArrays

a 夏天 提交于 2019-12-03 02:34:49
Skyler

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.

NSString *key;
for(key in someDictionary){
     NSLog(@"Key: %@, Value %@", key, [someDictionary objectForKey: key]);
}

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"]];
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!