Search code examples
iosmacoscocoansnotificationcenterkey-value-observing

What are the correct uses and differences of KVO and NSNotificationCenter?


Both KVO and NSNotificationCenter can deal with a value change. What's the difference between them? What's the correct use of them?


Solution

  • KVO is specifically for the change of properties.

    NSNotificationCenter can be used in a much broader context for all kinds of notifications, not only those dealing with property value changes. Plus, you can create your own notifications to send out to any other interested object that formerly subscribed to this notification as an observer.

    To create your custom notification use: [[NSNotificationCenter defaultCenter] postNotificationName:@"somethingHappened" object:nil];

    Another class can then subscribe to this notification with this code: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappenedSomewhere:) name:@"somethingHappened" object:nil];

    Whenever the method somethingHappenedSomewhere: will be called with the NSNotification as an argument.