does dealloc method being executed normally when quitting the application?

我的梦境 提交于 2019-12-17 20:51:55

问题


I use code like the following (inside my appController.m for example) to do some cleanup when my application terminates...

- (void) dealloc {
    [myObject release]; // myObject 's dealloc will not be called either !!!
    [arraySMSs release];
    [super dealloc];
}

This method never get called when the app quits! Why ? Is there a better place to do my clean up ? The fact that is not called addresses memory-leak issues ? Or the OS does take care of clean up ?

Thank you...


回答1:


There is no reason for the system to ensure that every object is individually deallocated upon application termination.

Doing so is just a waste of CPU cycles and a waste of the user's time.

When an app is terminated, all resources used by that app are reclaimed by the system in an entirely automatic and unavoidable fashion.

If you need something to happen at app termination, use the application delegate's hooks for doing so. But don't rely on that. A user may force reboot a device or force quit an application at whim.




回答2:


nice question, i was confused too.

now i got this:

Said that there's no object managed by our custom code that owes the appDelegate class itself, we don't really need to worry to "release" its instance. UIApplication is the only class that retain it, but we don't owe it.

But, for academic discussion or if there's any purpose i don't know at the moment, when you wanna test the dealloc in your appDelegate class:

applicationWillTerminate is the right place to know if your app is going to quit.

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [UIApplication sharedApplication].delegate = nil;
    // after this, the dealloc method of our appDelegate class will be called
}



回答3:


Here's the quote from NSObject Reference: "Important: Note that when an application terminates, objects may not be sent a dealloc message since the process’s memory is automatically cleared on exit—it is more efficient simply to allow the operating system to clean up resources than to invoke all the memory management methods." It pretty much confirms what many people have said.




回答4:


What makes you think dealloc is not being called? Have you run this is the debugger? Please see this question for why you won't necessarily be able to call NSLog in the dealloc method: when is dealloc executed?



来源:https://stackoverflow.com/questions/5079563/does-dealloc-method-being-executed-normally-when-quitting-the-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!