Given that objects may be deallocated even while a method invocation is in progress (link)*, is it safe for an object to register for and receive notifications that will be delivered on a thread that is different from the one on which it expects to be deallocated?

For reference, the documentation states that

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

Also important is the fact that NSNotificationCenter does not keep a strong reference to objects that are registered to receive notifications.

Here's an example that might make the situation more concrete:

- (id)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:SomeNotification object:nil];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)handleNotification:(NSNotification *)notification {
    // do something
}

An object with this implementation receives SomeNotification on thread X. Before -handleNotification: returns, the last strong reference to the object (in the code I can see) is broken.

  1. Am I correct in thinking that:

    a. If NSNotificationCenter takes a strong reference to the object before calling -handleNotification: on it, then the object will not be deallocated until after -handleNotification: returns, and

    b. if NSNotificationCenter does not take a strong reference to t

Edit
Report