2

我正在添加一个对象“m”,NSMutableArray如下所示:

    [m setObject:a forKey:@"a"];
    [m setObject:b forKey:@"b"];
    [m setObject:c forKey:@"c"];
    [m setObject:d forKey:@"d"];

    [myArray addObject:m];

    [m release];

对于一个对象,它可以正常工作,但是当添加另一个对象时,myArray 中的所有对象都会重复相同的值。

如何避免这种情况?

请帮忙。

谢谢。

4

2 回答 2

11

您需要在NSMUtablearray每次填充并插入它时创建一个单独的实例,否则您会继续重复使用相同的实例,因此只有它的最后一个状态出现在数组的每个位置。

NSMutableArray *myArray = [NSMutableArray array];
for (int i = 0 ; i != 10 ; i++) {
    NSMutableDictionary *m = [NSMutableDictionary dictionary];
    // Presumably, this part is done differently on each iteration
    [m setObject:a forKey:@"a"];
    [m setObject:b forKey:@"b"];
    [m setObject:c forKey:@"c"];
    [m setObject:d forKey:@"d"];
    [myArray addObject:m];
}
于 2012-05-17T00:43:10.793 回答
1

试试这个:

 NSMutableDictionary* m = [NSMutableDictionary dictionary];
[m setObject:@"1" forKey:@"a"];
[m setObject:@"2" forKey:@"b"];
[m setObject:@"3" forKey:@"c"];
[m setObject:@"4" forKey:@"d"];

NSMutableArray* myArray = [NSMutableArray array];
[myArray addObject:m];

NSLog(@"%@", m);
NSLog(@"%@", myArray);
于 2012-05-17T01:05:17.490 回答