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

后端 未结 3 494
后悔当初
后悔当初 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:50

    The object is deallocated on whatever thread releases the last strong reference to it. That is, whatever thread calls -release the final time. It is actually during that -release call that the object is deallocated.

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

    Decrements the receiver’s reference count. … The receiver is sent a dealloc message when its reference count reaches 0.

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

    1. Cleanup logic being executed on the wrong thread.

      If an object is autoreleased at an unexpected time, it will be deallocated on whatever thread’s autorelease pool block it happens to be in. This can easily be fatal for resources that should only be touched from one thread.

提交回复
热议问题