My app crashes in dealloc, but only sometimes.
I create one array for caching 5 objects. When the user taps right or left one, a new object is added and the last is removed. When I tested the app, after tapping the right or left button 100-500 times, the app crashes.
The app crashes in the dealloc method but all objects are allocated and released correctly.
My dealloc method :
- (void)dealloc
{
[super dealloc];
[_sImageLane release];
[_sTipoLane release];
[_maRecomended release];
[_maProdcucts release]; // here crash in this line EXC_BAD_ACCESSE
}
What is going wrong?
Put
[super dealloc]last instead of first.EDIT : The reason why this happens is due to the lifecycle of an objc object. When it is time for it to die, the object is sent the
deallocmessage. Inside that method, the object must clean itself up, and pass the message up the inheritance chain (because the super class needs to clean itself up as well). Well, what happens if you do that correctly with[super dealloc]being last?Nice, well what happens if you do it your way?
Oops, now you are accessing reclaimed memory and trying to interact with it (i.e. EXC_BAD_ACCESS or worse, messing with memory somewhere else on another object and not realizing it).
NSObject‘s dealloc method literally frees the memory (probably viafree()) so once you’ve called that you are in undefined dangerous gray areas.