Loop through NSDictionary to create separate NSArrays

后端 未结 3 425
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 18:20

I have a large NSDictionary that I need to loop through and create separate NSArrays. Here are the contents:

(
        {
        id =          


        
相关标签:
3条回答
  • 2021-02-05 18:53

    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"]];
    }];
    
    0 讨论(0)
  • 2021-02-05 18:55
    NSString *key;
    for(key in someDictionary){
         NSLog(@"Key: %@, Value %@", key, [someDictionary objectForKey: key]);
    }
    
    0 讨论(0)
  • 2021-02-05 19:02

    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.

    0 讨论(0)
提交回复
热议问题