Andrew Hershberger Andrew Hershberger - 1 year ago 92
Objective-C Question

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.

Answer Source

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]
 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download