2

我尝试将一些存储NSMutableDictionaries到一个NSMutableArraythrow a 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";
    }
)
4

1 回答 1

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,否则您将在右侧、左侧和中心泄漏字典...

于 2013-03-15T21:28:06.747 回答