Delegation and Data Sources
Have you ever needed to perform a task and had no idea how to do it? Maybe it's fixing a dishwasher or knitting a pair of socks. You can either learn to do it yourself, or find someone to help you with the parts you don't understand.
Cocoa Touch has a design pattern called delegation that lets your application help out system classes that don't know what you want to do. The way it works is simple: You introduce one object to another object that's able to answer any questions. By assigning a delegate, you provide hooks into code that can respond to requests and state changes.
If your object is willing to be a delegate, it needs to follow a protocol. As you saw on Follow the protocol, the protocol is like a contract. Many of the methods in that contract will be optional, but others will be required.
This pattern is used extensively throughout Cocoa. If you type delegate into the documentation viewer, you'll get back over 100 results. You can tell which classes support delegation, because they have a delegate property. The actual protocols for delegation are usually suffixed with Delegate.
The best way to see what this looks like in practice is by checking out one of the classes that uses delegation: the UIPickerView control that selects values from a scrolling list (Figure 3-2).

Figure 3-2. The standard picker view for Cocoa Touch. The values that are displayed ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access