NSMutableArray 未将数据正确存储到循环中 [英] NSMutableArray is not storing data properly into the loop

查看:39
本文介绍了NSMutableArray 未将数据正确存储到循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to store some NSMutableDictionaries into an NSMutableArray throw a for loop:

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,结果发现它包含上面循环的确切项目数,但只有一个值.

After the loop end, I try to debug the productsIdAndQuantities, and just came out that it contains the exact numbers of items looped above, BUT with one value.

我的意思是:

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

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

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

After the loop (NSLog(@"%@",productsIdAndQuantities);same value!!!!!):

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

推荐答案

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

You are adding the same dictionary into the array; use this instead, which allocates a new dictionary each iteration:

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

NOTE: This assumes you are using ARC, else you will leak dictionaries right, left and centre...

这篇关于NSMutableArray 未将数据正确存储到循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆