Sometimes program flow or logic flow can be disconnected while you are programming.
What does this mean? What I mean is something like this.
1. Try connecting to a web site which hosts RSS feeds
2. Obtain its HTML
2.1 Use NSURLConnection and set a delegate object in when calling initWithRequest:delegate method. Let’s call the delegate as connectionDelegate
2.2 In the connectionDelegate, whenever connection:didReceiveData: is called, each chunk of an HTML file will be gathered.
2.3 When connectionDidFinishLoading: is called, the connectionDelegate knows that all content of the HTML is retrieved. Then it should somehow tell the caller object that it received all the HTML and should ask the caller object to process with the HTML data
3. finds RSS feed URL from the HTML header
4. Parse an RSS file pointed by the feed URL
Between step 2.1 and 2.2 you will see that the execution flow of the caller object is stopped or cut. Then how the delegate object, connectionDelegate, inform the caller object to make the caller object continue?
You can use either notification or delegation.
How often do you use your own delegation or notification?
Using delegation, you set an object or a pointer to a class instance to a variable of another object. In above example, this “another object” is connectionDelegate. Although it sounds weird, what we call “delegate” here is not the connectionDelegate. In the connectionDelegate, when its connectionDidiFinishLoading: is called, a method of the delegate is called inside. This is direct call between object. So, there is no hidden cost. Good example of creating and using your own delegate is explained at CocoaDev Central.
Or you can set a notification observer and post notification when it calls connectionDidFinishLoading:.
When you use notification mechanism, Cocoa manages observers and what method to call when it happens. So, real difference is whether you manage (delegate) or Cocoa manages (notification).
Wait! However for notification, won’t multiple objects can get the notification message? Right. However, you can do it with your delegation mechanism. You set multiple delegate object and you can call each of them. Well.. though for notification, it is conveniently supported by Cocoa.
So, from framework writers’ point of view, they are very similar.
However, when we adopt such coding pattern, we should think about which approach is better.
For me.. convenience-wise, mostly notification seems to be better. Also sometimes it gives cleaner and more well-organized codes. However, it can be heavy.
So, if notification is too heavy for your case, try using delegation!