A delegate is a bunch of callback functions grouped together in one single class. To help you a little understand, suppose this method signature:
-[Foo doStuffWithInteger:(int)foo thenExecute:void (^block)(Foo*)]
(You know about blocks, right?) The documentation would tell that once the main algorithm of the method has completed, it will call back (execute) the block that was passed.
The delegate pattern is older, and does things a little different. With the delegate pattern, the Foo
class would have those two methods instead:
-[Foo setDelegate:(id)delegate]
-[Foo doStuffWithInteger:(int)foo]
Instead of invoking the block at the end of doStuffWithInteger
, the Foo
object would call a method on the delegate. This means the delegate must implement a certain method, say -[??? foo:(Foo*) completedStuffWithInteger:(int)]
, that the Foo
class will be able to use. All methods that need to call back would probably call a different method on the delegate.
Delegates in Objective-C generally let you implement custom behavior for classes without having to subclass them. For instance, CALayer
's delegate can implement the draw:inContext:
method, which is called when the layer needs to be drawn, and will provide content to the layer.
Since Objective-C is duck-typed, any class that implements the delegate methods can be used.