1

我是 iOS 开发的新手。基本上我有一个多维数组,如下所示

Array
(
[0] => Array
  (
  [Name] => Peter
  [Gender] => Male
  )
[1] => Array
  (
  [Name] => Glenn
  [Gender] => Female
  )
[2] => Array
  (
  [Name] => Richard
  [Gender] => Male
  )
)

在某个时候,我将在某个索引处添加额外的键/值。举个例子,我在数组末尾的索引 1 处添加一个新条目(序列实际上并不麻烦,它可以放在前面或末尾)[Location] => Japan

因此,数组应如下所示:

Array
(
[0] => Array
  (
  [Name] => Peter
  [Gender] => Male
  )
[1] => Array
  (
  [Name] => Glenn
  [Gender] => Female
  [Location] => Japan
  )
[2] => Array
  (
  [Name] => Richard
  [Gender] => Male
  )
)

我怎样才能做到这一点?请检查下面的代码,因为我真的不知道每次尝试都会导致 EXC_BAD_ACCESS 或应用程序被终止。在此先感谢,杰森。

for(int x=0; x<[arrayVisitor count]; x++)
{
  if ([[[arrayVisitor objectAtIndex:x]objectForKey:(@"Gender")]isEqual:@"Female"])
     [[arrayVisitor objectAtIndex:x] addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: @"Location",@"Japan",nil]];
}
4

1 回答 1

3

对于这种将键值对添加到数组的类型,您需要使用NSMutableArrayand NSMutableDictionary

NSMutableArray *outerArray=[[NSMutableArray alloc] init];

NSMutableDictionary *mutableDict=[[NSMutableDictionary alloc]initWithDictionary:[outerArray objectAtIndex:1]];
[mutableDict setObject:@"Japan" forKey:@"Location"];

[outerArray replaceObjectAtIndex:1 withObject:mutableDict];

或使用 for 循环作为:-----------------

NSMutableArray *arrayVisitor=[[NSMutableArray alloc] init];
int arrayLength=arrayVisitor.count;

for (int i=0;i<arrayLength;i++) {
    NSMutableDictionary *mutableDict=[[NSMutableDictionary alloc]initWithDictionary:[arrayVisitor objectAtIndex:i]];
    if ([[mutableDict valueForKey:@"Gender"] isEqualToString:@"Female"]) {
        [mutableDict setObject:@"Japan" forKey:@"Location"];
        [arrayVisitor replaceObjectAtIndex:i withObject:mutableDict];
    }
}

注意:- 它不是多维数组,它是 NSDictionary 对象的数组,应该是这样的

Array=(
       {
           Name= Peter
           Gender= Male
       },
       {
           Name = Glenn
           Gender = Female
       },
       {
           Name = Richard
           Gender = Male
       }
     )
于 2013-06-12T10:03:21.907 回答