NSNotification & NSNotificationCenter

NSNotificationCenter provides a centralized hub through which any part of an application may notify and be notified of changes from any other part of the application. Observers register with a notification center to respond to particular events with a specified action. Each time an event occurs, the notification goes through its dispatch table, and messages any registered observers for that event.

nshipster.com/nsnotification-and-nsnotificationcenter/

NSNotificationCenter acts as a central hub. Any part of an app can send notices or listen for changes from others. Observers sign up for certain events and get a callback when they happen. Each NSNotification has a name, an optional linked object, and a userInfo dictionary for extra info.

To add an observer, use addObserver:selector:name:object: or the block way addObserverForName:object:queue:usingBlock:. This returns an object to remove later. Remove with removeObserver: or removeObserver:name:object:. Post with postNotificationName:object:userInfo: or versions.

Names and userInfo keys are string constants. Posts happen on the current thread; move to main if needed. It differs from KVO, which watches key paths.

Notifications suit loose, spread-out talk for events in the app. Add them for key happenings; the cost is low.


Category:

Year: