NSNotificationCenter and safe multithreading

2019-02-06 22:29发布

问题:

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 the object before calling -handleNotification: on it, then the object may be deallocated before -handleNotification: returns

  2. Which way (a or b) does it work? I have not found this topic covered in the documentation yet, but it seems somewhat important to using NSNotificationCenter safely in a multithreaded environment.

UPDATE: The answer in the aforementioned link was updated indicating that "ARC retains and releases around an invocation on a weak reference". This means that an object should not be deallocated while a method invocation is in progress.

回答1:

I always recommend that if you're seeing notifications flying around on threads other than main, and you're seeing deallocations happen in the background, your threading may be too complicated. ObjC is not a thread-happy language. Most threading work should be in the form of short-lived blocks on queues. They can post notifications back to the main thread easily, but shouldn't be consuming notifications often.

That said, the best way today to manage multi-thread notifications is addObserverForName:object:queue:usingBlock:. This allows you much greater control over lifetimes. The pattern should look something like this:

__weak id weakself = self;
id notificationObserver = [[NSNotificationCenter defaultCenter]
 addObserverForName:...
 object:...
 queue:[NSOperationQueue mainQueue]
 usingBlock:^(NSNotification *note){
   id strongself = weakself;
   if (strongself) {
     [strongself handleNotification:note];
   }
 }];

Note the use of weakself/strongself. We're avoiding a retain loop using weakself. When we come back, we take a strong reference first. If we still exist, then we're locked-in for the rest of the block (so we can't dealloc in handleNotification:). If we don't exist, then the notification is discarded. (Note that weak references are effectively zeroed before calling dealloc. See objc_loadWeak.) I'm using mainQueue here, but you could certainly use another queue.

In the "old days" (pre-10.6), I designed around this problem by controlling object lifetimes. Basically, I designed such that short-lived objects didn't listen to notifications that might come from other threads. This was much easier than it sounds, because in pre-10.6 code, threading can be kept quite rare (and IMO, still should be kept to a low level). NSNotificationCenter was designed for that low-thread world.

Also note that unlike -[NSNotificationCenter addObserver:selector:name:object:], -[NSNotificationCenter addObserverForName:object:queue:usingBlock:] returns an opaque object that acts as the observer. You must keep track of this object so that you can remove the observer later on.



回答2:

NSNotificationCenter does not take a strong reference to the object, so the observer must be removed before deallocation. When ARC is enabled, if handleNotification is being called, the observer will not be deallocated since calling handleNotification will increase its retain count. If observer is deallocated before the notification is posted, NSNotificationCenter will remove it from the observers as you write in dealloc method so that handleNotification will not be called. NSNotificationCenter calls notification handlers synchronously while notification is posted.