NSNotificationCenter Block-based Observer

Back in iOS 4, a nifty block-based observer method was added to NSNotificationCenter:

- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block;

Super convenient, right? I love using blocks to pass simple callbacks to controllers instead of creating a delegate protocol. There is a catch with this method, and it’s not terribly obvious unless you’re looking closely. The method returns (id) – according to Apple’s documentation the return object is “An opaque object to act as the observer”.  What does this mean?

Typically when you register your class instance as an observer, you pair it with a removeObserver somewhere else usually in dealloc.  The thing is, removing self will NOT remove block-based observers! The opaque object that the method returned needs to be retained somewhere so that removeObserver can be called with that object. This is especially important if you’re calling self within the block to eliminate a retain cycle/memory leak.

Read more about the method and it’s usage in Apple’s documentation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s