user1412469
user1412469

Reputation: 279

Adding and modifying NSMutableArray inside NSMutableDictionary

I have a function in which an NSMutableDictionary is being populated by the values of an NSMutableArray. This NSMutableArray stores the CGPoints based on the movement of the finger. When touchesEnded is called, the values inside the NSMutableArray is "transferred" into the NSMutableDictionary, then it is emptied. I am doing this just to keep track on the finger movements (and for other purposes).

The problem here is that when the NSMutableArray is emptied, the NSMutableDictionary is emptied as well.

This is my code:

[pointDict setObject:pointArr forKey:[NSNumber numberWithInt:i]];
//When I check if the pointDict is not empty, it works fine.
[pointArr removeAllObjects];
//Now when I check if the pointDict is not empty, it returns nothing.

Can anyone tell me why is this happening? What's the problem with the code?

Upvotes: 0

Views: 735

Answers (1)

benzado
benzado

Reputation: 84308

When you call setObject:forKey: you are just passing along a pointer to the same object that pointArr is pointing to. So when you tell the array to removeAllObjects, all the points are gone, because there is only one array.

You need to make a copy before you store it. Assuming you are using ARC, and that you don't need to modify the array after you put it in the pointDict, you can do this:

[pointDict setObject:[pointArr copy] forKey:[NSNumber numberWithInt:i]];

If you need to keep the array mutable, you can use mutableCopy instead.

If you're not using ARC, you will need to use release or autorelease to release your claim on the the copied array after you put it in the dictionary (since copy creates a new object, just like alloc, you are responsible for releasing it).

Upvotes: 2

Related Questions