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?
When you call
setObject:forKey:you are just passing along a pointer to the same object thatpointArris pointing to. So when you tell the array toremoveAllObjects, 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:If you need to keep the array mutable, you can use
mutableCopyinstead.If you’re not using ARC, you will need to use
releaseorautoreleaseto release your claim on the the copied array after you put it in the dictionary (sincecopycreates a new object, just likealloc, you are responsible for releasing it).