Method
- (void)addObserver:(id)observer
forName:(NSString *)name
object:(id)object
queue:(NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *note, __weak id observer))block;
Usage
[[NSNotificationCenter defaultCenter] addObserver:self
forName:NSSomeNotificationName
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note, __weak id observer) {
NSLog(@"self: %@", observer); //Look Ma, no leaks!
}];
Discussion
The observer object takes the place of the token in the current block-based API and works like the observer in the selector-based API. The block is retained by NSNotificationCenter only for as long as the observer exists. NSNotificationCenter does not retain the observer, so if all other references are deleted it will be destroyed, along with the block.
For convenience, a weak reference to the observer is passed as a second parameter to the block. The block can use this to refer to the observer (which would be 'self' in typical usage) to avoid doing the weakify dance.
There is no need to call removeObserver: in the observer's dealloc method, as the observer reference is cleaned up automatically when the observer is released. To remove the observer before it is released, you can use the existing removeObserver: APIs.
@jwilling yours suffers from the same design flaw as my (1.0) version did, that there is no way to explicitly deregister the notifications again except by allowing the observer to be released.
I was hoping there was a way to do it by having the observer object act as a proxy for the real observers (see version 1.0.1), but that ended up being way more complicated, and in any case didn't work properly as the associated objects weren't cleaned up correctly.
I eventually managed to solve this (in version 1.0.2) by swizzling removeObserver:name:object: to manually release the associated observers (tokens in your case) for the object.