Search code examples
iosobjective-cnsarraynsdictionary

How to add key to NSMutableArray


I have a NSMutableArray looks like this. And I want to pass this Array to another ViewController and use the elements of it. But I'm confused about how to add keys to each element. For example, {@"bus_route_key":@"733"}

Is there a way to init the Array with keys? Or should i create NSDictionary for this?

@[
 @[
  @733,
  @"Oakleigh - Box Hill via Clayton & Monash University & Mt Waverley",
  @"Oakleigh Railway Station/Johnson St",
  @"2016-04-05T11:44:00Z"
  ],
 @[
  @631,
  @"Southland - Waverley Gardens via Clayton & Monash University",
  @"Southland Shopping Centre/Karen St",
  @"2016-04-05T11:46:00Z"
  ],
 @[
  @703,
  @"Middle Brighton - Blackburn via Bentleigh & Clayton & Monash University (SMARTBUS Service)",
  @"Luntar Rd/Centre Rd",
  @"2016-04-05T11:50:00Z"
  ]
 ];

Solution

  • NSArray *mainArray = @[
     @[
      @733,
      @"Oakleigh - Box Hill via Clayton & Monash University & Mt Waverley",
      @"Oakleigh Railway Station/Johnson St",
      @"2016-04-05T11:44:00Z"
      ],
     @[
      @631,
      @"Southland - Waverley Gardens via Clayton & Monash University",
      @"Southland Shopping Centre/Karen St",
      @"2016-04-05T11:46:00Z"
      ],
     @[
      @703,
      @"Middle Brighton - Blackburn via Bentleigh & Clayton & Monash University (SMARTBUS Service)",
      @"Luntar Rd/Centre Rd",
      @"2016-04-05T11:50:00Z"
      ]
     ];
    
    NSMutableArray *newArray = [NSMutableArray array];
    
    for (NSArray *arr in mainArray) {
    
            NSDictionary *dict = @{
                                   @"key1" : [arr objectAtIndex:0],
                                   @"key2" : [arr objectAtIndex:1],
                                   @"key3" : [arr objectAtIndex:2]
                                   };
    
        [newArray addObject:dict];
    }
    
    DLOG(@"New Arr : %@", newArray);
    
    //you can access by key like this
    
    for (NSDictionary *dict in newArray) {
    
        DLOG(@"%@", [dict valueForKey:@"key1"]);
        DLOG(@"%@", [dict valueForKey:@"key2"]);
        DLOG(@"%@", [dict valueForKey:@"key3"]);
    }
    

    Hope it'll help you..:)