我曾经吃过亏,当你遍历一个NSMutableArray
对象时,你不能从其中移除对象。
通过循环[< array_object > copy]
而不是< array_object >
可以解决这个问题。
然而,我有一些未解答的问题,希望Objective-C专家能提供帮助。
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) }
removeObject
知道要删除哪个对象,因为它是一个浅拷贝,这意味着原始容器和副本中的字典实际上是内存中相同的对象。它们具有相同的地址、相同的内容等等。这就是为什么删除操作没有问题定位它们的原因。 - Sergey Kalinichenko