Malloc
Malloc

Reputation: 16276

NSMutableArray is not storing data properly into the loop

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";
    }
)

Upvotes: 2

Views: 333

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

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...

Upvotes: 6

Related Questions