Cocoa delegates are used to accomplish inversion of control and lessen the need for subclassing. It's entirely possible to have multiple delegates for a single object, but this is done when it makes sense to delegate different kinds of decisions to different objects. A great example of this is
WebView from WebKit, which has five delegates responsible for areas as diverse as resource loading and navigation policy.
C#'s event–delegate system, which allows an object to register with another object to be notified when a particular event occurs, is closest to the several notification APIs available from Cocoa. The various APIs you might run across are, from highest level to lowest:
- Darwin notifications.
All are similar in spirit, so I'll only consider the one you'd use in this case:
Observers, such as ClassA and ClassB, register their interest in notifications with
NSNotificationCenter. They can specify an interest in
- notifications with a specific name from a specific object
- notifications with a specific name from any object
- notifications from a particular object.
When a matching notification is posted to the notification center, observers are notified by invoking the method they supplied at registration time with the notification center. The method always has the same type: it returns nothing and accepts a single argument, an
You would generally handle your situation by having ClassC declare a constant for the notification name in its header file, for example,
extern NSString *const ClassCSomethingDidHappenNotification;
Interested observers, such as ClassA and ClassB, can then register interest in this notification:
Instead of registering a selector and adding a method to the observer to handle the callback, you can also now register an operation queue and a block to execute on that queue when a matching notification is posted.
When the event associated with the notification occurs, ClassC posts the notification to the notification center:
The notification center will then look through the list of observers, find those that match this notification, and invoke the appropriate method.