NSMutableArray没有正确地将数据存储到循环中

时间:2013-03-15 21:25:26

标签: ios nsmutablearray

我尝试将一些NSMutableDictionaries存储到NSMutableArray一个for循环中:

NSMutableArray *productsIdAndQuantities = [[NSMutableArray alloc]init];
NSMutableDictionary *element = [[NSMutableDictionary alloc]init];

for (id object in shoppingArray) {
    [element setObject:[object valueForKey:@"proId"] forKey:@"id"];
    [element setObject:[object valueForKey:@"qty"] forKey:@"quantity"];
    NSLog(@"%@",element);//tested, it's different on every iteration
    [productsIdAndQuantities addObject:element];
}

循环结束后,我尝试调试productsIdAndQuantities,刚出来它包含上面循环的项目的确切数量,但只有一个值。

这就是我的意思:

在循环内部(NSLog(@"%@",element);):

{
    id = 13293;
    quantity = "-2";
}
{
    id = 12632;
    quantity = "-5";
}

循环后(NSLog(@"%@",productsIdAndQuantities);相同值!!!!!):

(
    {
        id = 12632;
        quantity = "-5";
    },
    {
        id = 12632;
        quantity = "-5";
    }
)

1 个答案:

答案 0 :(得分:6)

您正在将相同的字典添加到数组中;改为使用它,每次迭代都会分配一个新的字典:

NSMutableArray *productsIdAndQuantities = [[NSMutableArray alloc]init];
for (id object in shoppingArray) {
    NSMutableDictionary *element = [[NSMutableDictionary alloc]init];
    [element setObject:[object valueForKey:@"proId"] forKey:@"id"];
    [element setObject:[object valueForKey:@"qty"] forKey:@"quantity"];
    NSLog(@"%@",element);//tested, it's different on every iteration
    [productsIdAndQuantities addObject:element];
}

注意:这假设您正在使用ARC,否则您将向右,左和中间泄漏词典...