NSMutableArray is not storing data properly into the loop

那年仲夏 提交于 2019-12-12 18:32:37

问题


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];
}

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.

Here is what I mean:

Inside the loop (NSLog(@"%@",element);):

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

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

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

回答1:


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];
}

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



来源:https://stackoverflow.com/questions/15442345/nsmutablearray-is-not-storing-data-properly-into-the-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!