AddingRemoving an Observer with a Block

suggest change

Instead of adding an observer with a selector, a block can be used:

id testObserver = [[NSNotificationCenter defaultCenter] addObserverForName:@"TestNotification"
                                                                    object:nil 
                                                                     queue:nil // nil runs the block on the posting thread
                                                                usingBlock:^(NSNotification* notification) {
    NSDictionary *userInfo = notification.userInfo;
    MyObject *myObject = [userInfo objectForKey:@"someKey"];
}];

Remove the block observer with the token from addObserverForName:object:queue:usingBlock:. Do not pass that token to removeObserver:name:object:; that form does not reliably remove block-based observers.

[[NSNotificationCenter defaultCenter] removeObserver:testObserver];

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents