One of the common examples given of informal protocols is to define callbacks. Suppose you are using a library that lets you download something in the background. This library lets you register a callback object to be called when complete.
- (void)download:(NSURL*)url whenComplete:(id)callback
When the download is complete, it will call a particular method on your callback object:
- (void)downloadComplete:(NSURL*)url
Of course, there is no guarantee that your callback object actually implements this method. Informal protocols provide trivial implementations of these methods on NSObject
, using a category. As a result, all objects in the system will respond to the downloadComplete:
method, though they will do nothing in response to that method by default. Classes that override the downloadComplete:
method can provide more useful functionality.
So far, you can accomplish the same thing with a formal protocol. However, informal protocols allow you to have optional methods. A class that implements a formal protocol must provide an implementation for every method in the protocol. A class implementing an informal protocol can omit implementation for any method - it has already inherited an implementation from NSObject
.
Since Objective-C 2.0, formal protocols can contain optional methods. In addition, Apple might be moving away from informal protocols for new APIs - UIAccelerometerDelegate
is a formal protocol.
callback
is potentially confusing here, especially in a world where blocks exist. What you're talking about is delegation. (I realize that this answer probably made more sense in 2010.) – Policyholder