我正在向NSMutableArray
添加一个对象“m”,如下所示:
[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中的所有对象重复相同的值。
如何避免这种情况?
请帮忙。
感谢。
答案 0 :(得分:10)
每次填充和插入时都需要创建一个单独的NSMUtablearray
实例,否则你会继续重复使用同一个实例,因此只有它的最后一个状态出现在数组的每个位置。 / p>
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];
}
答案 1 :(得分: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);