NSNotificationCenter Category Providing An Easier Blocks Based API Without The Memory Issues

Blocks have been a nice addition to iOS Objective-C programming, but unfortunately the blocks-based API added to NSNotificationCenter brings about a number of potential issues.

Here’s a library from Nick Lockwood called FXNotifications that provides an NSNotificationCenter category that provides an easier to use blocks based API but allows you to avoid memory leak and retain cycle bugs that can occur when simply using the official API.

Here’s an example from the readme showing the method added with FXnotifications in action:

[[NSNotificationCenter defaultCenter] addObserver:self
                                          forName:NSSomeNotificationName
                                           object:nil
                                            queue:[NSOperationQueue mainQueue]
                                       usingBlock:^(NSNotification *note, __weak id observer) {
                                                      NSLog(@"self: %@", observer); // look, no leaks!
                                                  }];

Notice that you must specify an observer for the method to work.

You can find FXNotifications on Github here.

You can read more about the issues when using blocks and NSNotificationCenter without FXNotifications on the Sealed Abstract blog.

A handy category making NSNotificationCenter easier to use while avoiding some major issues.

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: NSNotificationCenter Category Providing An Easier Blocks Based API Without The Memory Issues

©2013 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *