Search code examples
objective-ciosarchitectureobserver-patternnsnotificationcenter

When to use NSNotificationCenter


I want to have multiple observers on multiple events of a single object (1-to-N relationship).

A mechanism to achieve this task is provided by the NSNotificationCenter. The mechanism looks pretty overkill when used for my problem.

How I would do it manually without the use of NSNotificationCenter:

- (void)addDelegate:(id<DelegateProtocol>)delegate;
- (void)removeDelegate:(id<DelegateProtocol>)delegate;

to add and remove observers from my object.

- (void)someEventFired:(NSObject<NSCopying> *)eventData
{
    for (id delegate in delegates) {
        NSObject *data = [eventData copy];
        [delegate someEventFired:data];
    }
}

This mechanism is straight-forward and simple to implement without the objects having to share additional strings.

  • Is there an official pattern for 1-to-N delegates (like C# events) in an iOS framework besides the NSNotificationCenter?
  • When should the NSNotificationCenter be used and when not?
  • When should an implementation like the one I am suggesting here be used and when not?

Solution

  • By convention, delegates should probably only be used for 1:1 relationships. If you really need 1:N relationships for this type of functionality, you have two options:

    1. As you mentioned, NSNotificationCenter.
    2. Key-Value Observing (also known as KVO).

    KVO is appropriate if you only care about when a particular property of an object changes. Otherwise, you should really just consider using NSNotificationCenter. You can even be notified only when a specific object posts that notification by passing that object into the addObserver:selector:name:object: method.

    Apple uses NSNotification in similar scenarios (like the notifications defined for UITextField, including UITextFieldTextDidBeginEditingNotification, UITextFieldTextDidChangeNotification, and UITextFieldTextDidEndEditingNotification).