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.
NSNotificationCenter
?NSNotificationCenter
be used and when not?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:
NSNotificationCenter
.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
).