Should dealloc be called on the same thread that created the object?

Is dealloc guaranteed to be called on the same thread that created the NSObject instance? For example, if I call [[MyFluffyBunny alloc] init] in the main thread, is it guaranteed to also be called in the dealloc main thread, or can it be called in any thread once MyFluffyBunny no longer saved?

I see sporadic failures in my application, which indicate that they are not guaranteed, but I could not find the documentation confirming it.

+6
source share
3 answers

The object is freed from the fact that the thread releases the last strong reference to it. That is, any thread causes -release final time. In fact, during this call, the -release object is freed.

The documentation for the -release method in the NSObject protocol states:

Decreases the recipient link count .... A dealloc message is sent to the recipient when its link count reaches 0.

Advanced Memory Management Programming Guide: The Practical Memory Management article includes the following: reasons not to use -dealloc to manage scarce resources :

  1. The cleanup logic is executing in the wrong thread.

    If the object is auto-implemented at an unexpected time, it will be freed from any autostart thread pool in which it is located. This can be easily fatal for resources that need to be affected from only one thread.

+8
source

There is no such guarantee and, in fact, it causes some subtle errors when using KVO (and bindings on OS X).

You can easily see it in action by creating an object that registers [NSThread currentThread] during init and dealloc , then runs the code, for example:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { Testing *testing = [[Testing alloc] init]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ NSLog(@"Use testing in background: %@", testing); }); testing = nil; return YES; } 
+2
source

I don't know the line in the documentation that says this, but here are a few points of logic:

  • If you cannot find a guarantee anywhere, assume that it does not exist. (It looks like you already know about it, and hope for hope that someone else can tell you what gives you the answer you want)

  • This requirement may not be possible, because you can build something in the stream, and then terminate this stream, and then output the last link from an area somewhere else in some other stream. At the moment, it would be impossible to dealloc in the old thread, because it no longer exists.

+1
source

All Articles