Usage of delegates is prevalent throughout the SDK’s that Apple provides. A delegate is basically a way to tell a standard object “Hey you, if you need some info or want to inform somebody when something happens, talk to this guy. I’m outta here”.
This achieves three things that are an essential skills in programming:
- you make use of a component without having to do extra work of subclassing it for customization
- you appoint somebody else to do the work of one-the-fly customizing (the delegate)
- you can excuse yourself and go to the pool
A good example of usage of delegates is UITableView. This standard class, to be found in UIKit, knows and speaks two protocols: UITableViewDataSource and UITableViewDelegate. As the names suggest the first deals with questions related to the content of the table to be displayed: number of sections, number of rows, headers, individual row cells et cetera. The second delegate, which is also called delegate, deals with interactions on a higher level, like if you tapped on an individual cell. Even though they are called different, both are delegation protocols and if you like you can assign discrete classes to data source and delegate for a table view.
To make this a practical example I will show how to make a class that informs your code when a headset is plugged in or plugged out.