I learnt the hard way that you can't remove objects from an NSMutableArray
when you are looping through the objects in it.
Looping through [< array_object > copy]
instead of < array_object >
fixes it.
However, I have a few unanswered questions that I would like input on from the Objective-C gurus.
In this first for loop, I expected each of the
nextObject
s to point to different memory (i.e I thought themsgDetail
array will have a list of pointers, each pointing to the address of theNSDictionary
that a particular array index contains). But all of the%p nextObject
prints are giving the same value. Why is that?for(NSDictionary *nextObject in msgDetailArray) { NSLog(@"Address = %p, value = %@",&nextObject,nextObject) ; //Doing [msgDetailArray removeObject:nextObject] here based on some condition fails }
In the second for loop, the address of the
nextObject
NSDictionary
s are different from that printed in the first for loop.for(id nextObject in [msgDetailArray copy]) { NSLog(@"In copy Address = %p, value = %@",&nextObject,nextObject) ; //Doing [msgDetailArray removeObject:nextObject] here based on some condition succeeds and it also removes it from the original array even though I am looping through a copy }
However, when I loop through
[msgDetailArray copy]
, and then do aremoveObject:
, it removes it from the originalmsgDetailArray
. How doesremoveObject:
do this? Does it actually use the contents of the dictionary and remove an object that matches the content? I thought all it does is to check if there is an object that is in the same memory location and remove it (Based on 2, I assume the memory address containing the dictionaries in[msgDetailArray copy]
are not the same as the addresses in the originalmsgDetailArray
). If it is actually using contents, I will have to be very careful in case there are duplicate entries.for(id nextObject in msgDetailArray) { NSLog(@"Address = %p, value = %@",&nextObject,nextObject) ; //test what is left in msgDetailArray. I see that doing removeObject on [msgDetailArray copy] does remove it from the original too. How is removeObject working (is it actually contents of dictionary) }