如何将键添加到NSMutableArray

时间:2016-04-05 12:14:20

标签: ios objective-c nsarray nsdictionary

我有<GridView.ItemContainerStyle> <Style TargetType="GridViewItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </GridView.ItemContainerStyle> 看起来像这样。我想将此Array传递给另一个ViewController并使用它的元素。但我对如何为每个元素添加键感到困惑。例如,NSMutableArray

有没有办法用键启动数组?或者我应该为此创建{@"bus_route_key":@"733"}吗?

NSDictionary

6 个答案:

答案 0 :(得分:1)

哇,嘿,Melbournian。

你应该有一个包含NSMutableDictionaries的NSMutableArray,并设置每个总线更加结构化:

(
  {
    "route": 733,
    "line_name": "Oakleigh - Box Hill via Clayton & Monash University & Mt Waverley",
    "stop": "Oakleigh Railway Station/Johnson St",
    "time": "2016-04-05T11:44:00Z"
  },

  //Insert other line dictionaries
)

答案 1 :(得分:0)

目前,您的NSMutableArray包含NSArrays。在您的情况下,这些NSArray需要为NSDictionaryNSMutableDictionary

然后你可以编辑bus_route_key例如第一个元素,如下所示: [[yourList objectAtIndex:0] setInteger:1337 forKey:@"bus_route_key"] 如果要设置字符串,则需要使用setObject

答案 2 :(得分:0)

您可以将NSArray转换为NSDictionary,因为数组不包含键,值数组只有索引

答案 3 :(得分:0)

我的代码会帮助您:)

  NSMutableArray *arrTitles = (NSMutableArray *)@[@{
     "route": 733,
     "line_name": "Oakleigh - Box Hill via Clayton & Monash University & Mt Waverley",
     "stop": "Oakleigh Railway Station/Johnson St",
     "time": "2016-04-05T11:44:00Z"
      },@{
    "route": 733,
    "line_name": "Oakleigh - Box Hill via Clayton & Monash University & Mt Waverley",
    "stop": "Oakleigh Railway Station/Johnson St",
    "time": "2016-04-05T11:44:00Z"
  }];

答案 4 :(得分:-1)

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"]);
}

希望它能帮助你...... :)

答案 5 :(得分:-1)

使用下面的代码行:
    NSMutableDictionary * dict2 = [[NSMutableDictionary alloc] initWithObjects:attributeValues forKeys:attributeKeys];

此处,attributeValues是值NSArray的{​​{1}},而attributeKeys是键的NSDictionary

请参阅以下参考链接:

http://hayageek.com/nsdictionary-nsmutabledictionary/

NSArray