views:

165

answers:

5

I decided to start using removeAllObjects so that I could re-use some of my NSMutableArrays. However, I am finding that the call to removeAllObjects causes the array to get released and so it crashes when the viewController is displayed for the second time.

I've looked on the web and it seems that some people are saying that removeAllObjects just clears their array, while others are saying that it also releases the array. Which is true? It appears to release for me, but I find that weird and would expect the behaviour to be just to release the objects within the array. Nothing in the documentation warns of this, which I also find strange.

EDIT: With NSZombies turned on, all I get back is:

  • -[__NSArrayM removeAllObjects]: message sent to deallocated instance 0x625e4e0

Basically telling me that because the array was released due to the removeAllObjects, it can't call removeAllObjects second time round... Argh!

Can anyone help please?

Thanks!

+2  A: 

removeAllObjects does not release the array itself, as you rightly expect. If it is being released the problem is somewhere else. You can use the NSZombie's instruments to check where it is being released.

Mo
Unfortunately all NSZombie tells me is: *** -[__NSArrayM removeAllObjects]: message sent to deallocated instance 0x625e4e0
Joe
+1  A: 

If you are autoreleasing your MutableArrays, they might be released when they are empty as they are after a call to removeAllObjects. Use NSZombies to look where it is released exactly.

Gauloises
Unfortunately all NSZombie tells me is: * -[__NSArrayM removeAllObjects]: message sent to deallocated instance 0x625e4e0
Joe
then your array is already released before you call remove all objects, hence this call has nothing to do with it being dealloc'd
Gauloises
I found the problem... Will add it below... I was being a numpty :-)
Joe
+1  A: 

removeAllObjects releases the objects in the array but has no effect on the array itself (except to make it empty).

Unless

one or more of the objects in the array had a retained reference to the array itself.

JeremyP
nice idea! But I made a really stupid error... Will answer below.
Joe
+1  A: 

Okay so I was being an idiot!

I was doing:

[myArray removeAllObjects];
myArray = someOtherObject.someArray;

therefore resetting the pointer to some other object. I've now changed it to this:

[self.myArray removeAllObjects];
[self.myArray addObjectsFromArray:someOtherObject.someArray];

And it's now okay. I'm an idiot! Sorry all, thanks for your help!

Joe
+1  A: 

NSZombies can't tell you where the object is being released, so it shows you the first time you send a message to the deallocated object.

Work backward from that call to -removeAllObjects, and you'll find the bug.

Sidnicious