NSNotificationCenter and safe multithreading

后端 未结 2 569
青春惊慌失措
青春惊慌失措 2020-12-31 18:08

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 notificati

2条回答
  •  北海茫月
    2020-12-31 19:03

    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.

提交回复
热议问题