views:

263

answers:

2

I have noticed whist learning how Cocoa-Touch works over the last few weeks that dealloc methods don't seem to be getting called when I exit the app in the iPhone simulator. Now to be fair I am not doing anything too scientific just putting in NSlog statements that can print to the console. My questions is:

(1) Does the simulator disconnect from Xcode on app exit stopping my NSLogs echoing to the console?

(2) Are deallocs not called as an optimisation, because the app is exiting anyways?

(3) Would the deallocs get called when the app is running on actual iPhone hardware?

gary

A: 

As dreamlax already said, the system reclaims all memory as soon as the application exits. So there is no use for the application to call dealloc when quitting. It's standard behaviour on Mac OS X, and I doubt it will be different on an iPhone - simulated or "real".

Matthias Gansrigler
+4  A: 

The docs say that it is more efficient for the operating system to reclaim the memory all at once than for the application to slowly relinquish all of its chunks of memory. For this reason, dealloc may not be sent to a vast number of objects; and for this reason it is important not to manage scarce resources in dealloc. To clean up scarce resources it is probably a better idea to have your application delegate respond to applicationWillTerminate: and do your cleanup in there.

- (void) applicationWillTerminate:(NSApplication/UIApplication *) anApp
{
    [scarceResourceManager relinquishScarceResources];
}
dreamlax
To be blunt: Spending CPU cycles calling `free()` or `-deallocate` when an app is terminating is a complete and total waste of resources. Both Mac OS X and iPhone use a memory model where each process is kept in isolation. When a process terminates, *all* memory resources related to that app are reclaimed all at once.
bbum
Thank you dreamlax and bbum, its something that has been bugging me for a while, much appreciated.
fuzzygoat
Both of dreamlax and bbum are right. Freeing memory at termination is waste but important thing is there are many thing to do when terminating except freeing memory. And this posting is valuable for those cases.
Eonil