At the moment I am teaching myself iOS programming, and one concept I find really hard to wrap my head around is delegation. What is it? Why and how is it used? What is the advantage? The technical writing from the book I'm reading makes it hard to understand.
Apple uses delegation pervasively. More and more, though, you're seeing Apple move a lot of their API over to
That being said, delegation helps maintain MVC, even though I would argue delegation is a design pattern in and of itself. It helps to separate models from controllers. Such as in John Cartwright's example, a
More than that, you're not locked into one delegate for the entire lifetime of an object. You could very easily have multiple datasources for a given
So, on the one hand, delegation is great for supplying data to and responding to interactions from an object. You'll see it in a lot of UIKit classes, such a
But delegation is also very useful when you want to pass information between objects. You can very easily create your own protocols and sign up your own objects to follow them. Furthermore, protocol methods are
In MyChildViewController, when your button is tapped, simply check if your delegate responds to the delegate message (if it's required and your delegate doesn't implement the method, you'll crash. You can make the method
Then set the delegate of your MyChildViewController to
NOTE: Delegates should be weak/assign properties, otherwise you'll enter a retain cycle where neither object can be deallocated.
Hope this helps!
Delegates are objects that implement certain functions when it doesn't make sense to implement those functions on the normal object. It is a form of dependency injection.
For a concrete example, look at the UITableViewDelegate protocol. These methods don't make sense for a table view to implement directly, because actions for selecting a table view row will be different in each app and maybe in each table view. The delegate has a method