iOS, Objective-C, Swift, Design and Whatever Comes in Mind
‹ Back to the Blog

NSNotification

One of my favorite new features in iOS 9:

Objects that have registered to NSNotificationCenterare now weak referenced and therefore there is no need about un-register a given observer.
🎉

It gets far less attention as I expected, due to the fact, that it makes using NSNotification much simpler.

Prior to iOS 9, you have to keep track of all every notification name that you have registered to the NSNotificationCenter.
Once the registered object will be de-allocated, you have to un-register it manually. Otherwise, it will be kept in memory and cause a crash if the desired notification is fired.

Whether you use
addObserver(_ notificationObserver: AnyObject, selector notificationSelector: Selector, name notificationName: String?, object notificationSender: AnyObject?)

or the newer block-based approach
addObserverForName(_ name: String?, object obj: AnyObject?, queue queue: NSOperationQueue?, usingBlock block: (NSNotification!) -> Void) -> NSObjectProtocol,
you don't have to answer questions like when does this object gets removed or when will this UIViewController disappear.

"NSNotification".