I always recommend that if you see notifications that fly around threads other than the main one, and you see that maladaptation occurs in the background, your streaming may be too complicated. ObjC is not a no-man's language. Most thread operations should be in the form of short-lived blocks in queues. They can send notifications back to the main thread easily, but they should not use notifications often.
However, the best way to manage multi-threaded notifications is addObserverForName:object:queue:usingBlock: This can significantly increase the lifetime. The template 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]; } }];
Pay attention to the use of the weak / oneself. We avoid a closed loop using weakness. When we get back, first take a strong link. If we still exist, then we are locked for the rest of the block (therefore, we cannot dealloc in handleNotification: . If we do not exist, the notice is discarded. (Note that weak links are actually nullified before calling dealloc . See objc_loadWeak .) I use mainQueue here, but you can, of course, use a different queue.
In the "old days" (before 10.6), I developed this problem by controlling the lifetime of the object. In principle, I designed such that short-lived objects did not listen to notifications that might arise from other threads. It was much simpler than it seems, because in code up to 10.6 streams can be stored quite rarely (and IMO, nevertheless, needs to be kept low). NSNotificationCenter was designed for this low-flow world.
Also note that unlike -[NSNotificationCenter addObserver:selector:name:object:] , -[NSNotificationCenter addObserverForName:object:queue:usingBlock:] returns an opaque object that acts as an observer. You must track this object so that you can remove the observer later.
Rob napier
source share