NSNotificationCenter and safe multithreading

孤街浪徒 提交于 2019-11-30 09:16:16
Rob Napier

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!