我在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]];
}
答案 0 :(得分:3)
对于此类型的数组添加键值,您需要使用NSMutableArray
和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
}
)