Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter and safe multithreading

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.

like image 377
Andrew Hershberger Avatar asked Dec 06 '12 13:12

Andrew Hershberger


People also ask

Is Nsnotificationcenter thread safe?

No. Apple's docs on the subject say: "Regular notification centers deliver notifications on the thread in which the notification was posted. [...] At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center.

What is NSNotification in Swift?

An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.


1 Answers

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.

like image 184
Rob Napier Avatar answered Oct 23 '22 10:10

Rob Napier