Is dealloc guaranteed to be called on the same thread that created the object?

后端 未结 3 490
后悔当初
后悔当初 2020-12-16 04:14

Is dealloc guaranteed to be called on the same thread that created a NSObject instance? For example, if I call [[MyFluffyBunny alloc] init]

3条回答
  •  一整个雨季
    2020-12-16 04:39

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

    You can see it in action fairly easily by creating an object that logs [NSThread currentThread] during init and dealloc, then running code such as:

    - (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;
    }
    

提交回复
热议问题