什么时候发布'autorelease'的对象?

时间:2021-03-18 09:37:32

I'm developing for iPhone, objective-c. When we use autorelease, when does the object actually get released - when the main autorelease pool gets released (ie. the application terminates?), or as soon as the local function ends? For example, I want to do something like this:

我正在开发iPhone,objective-c。当我们使用自动释放时,对象实际上何时被释放 - 当主自动释放池被释放时(即应用程序终止?),或者本地函数何时结束?例如,我想做这样的事情:

- (void) test
{
    MyObj* p = [[[MyObj alloc] init] autorelease];
    ...

    // is p 'released' here?
}

So is 'p' released as soon as the function exits, or when the autorelease pool of this thread is released? I thought it was when the local function exits, but I just created my own thread and needed to setup an autorelease pool which is giving me second thoughts on when this actually happens..

一旦函数退出,或者当该线程的自动释放池被释放时,'p'就会被释放吗?我认为这是当本地函数退出时,但我只是创建了自己的线程,并需要设置一个自动释放池,这让我第二次想到这实际发生的时间..

Thanks

2 个解决方案

#1


An autoreleases object is released the same time the autorelease pool is. So for your thread it will be released when you release the pool. In the main thread, if you don't create your own, I believe the autorelease pool is drained every time through the run loop -- but I haven't looked at in a while.

autoreleases对象在自动释放池的同时释放。因此,对于您的线程,它将在您释放池时释放。在主线程中,如果你不创建自己的,我相信自动释放池每次都会在运行循环中耗尽 - 但我有一段时间没有看过。

#2


As Argothian says, it is released when the autorelease pool is released, which happens every time through the run loop in a normal Cocoa application, not at application termination (unless of course you don't have a run loop, in which case you have to create the autorelease pool, and release it yourself). Autorelease pools don't know about each individual function call, and so could not release things at the end of a function call.

正如Argothian所说,它是在释放自动释放池时释放的,每次通过正常Cocoa应用程序中的运行循环时都会释放,而不是在应用程序终止时(除非你没有运行循环,在这种情况下你有创建自动释放池,并自己释放它。自动释放池不知道每个单独的函数调用,因此无法在函数调用结束时释放内容。

#1


An autoreleases object is released the same time the autorelease pool is. So for your thread it will be released when you release the pool. In the main thread, if you don't create your own, I believe the autorelease pool is drained every time through the run loop -- but I haven't looked at in a while.

autoreleases对象在自动释放池的同时释放。因此,对于您的线程,它将在您释放池时释放。在主线程中,如果你不创建自己的,我相信自动释放池每次都会在运行循环中耗尽 - 但我有一段时间没有看过。

#2


As Argothian says, it is released when the autorelease pool is released, which happens every time through the run loop in a normal Cocoa application, not at application termination (unless of course you don't have a run loop, in which case you have to create the autorelease pool, and release it yourself). Autorelease pools don't know about each individual function call, and so could not release things at the end of a function call.

正如Argothian所说,它是在释放自动释放池时释放的,每次通过正常Cocoa应用程序中的运行循环时都会释放,而不是在应用程序终止时(除非你没有运行循环,在这种情况下你有创建自动释放池,并自己释放它。自动释放池不知道每个单独的函数调用,因此无法在函数调用结束时释放内容。