Key Concepts: Custom Delegation

Delegation is a design pattern that allows objects to communicate with each other. Many of Apple's classes use delegation to request required information from you, for example, UITableView asks you how many rows it should display, and asks you to provide each cell as it needs to display them on the screen. Apple also uses delegation to communicate state changes to you, eg. UIWebView tells you that it has started loading its web page and UIAlertView tells you when the user has pressed a button.

Custom delegation is tricky and involves four steps:

  1. Create a @protocol
  2. Implement that protocol in a class (eg. @interface Foo < UITableViewDelegate >)
  3. Add a delegate property to the class that the protocol applies
  4. Set the delegate property to an instance of the class that implements the protocol

Eg. a BeligerantChild class may have an associated BeligerantChildDelegate protocol. The BeligerantChild will have a @property id< BeligerantChildDelegate > delegate and a ViewController will implement the delegate protocol (@interface ViewController < BeligerantChildDelegate >). The BeligerantChild will call the protocol's methods on its delegate property.

A key understanding in Custom Delegation is that the delegate property and the self variable in the ViewController are the same.

Xcode Tips
CMD + 0 to close the left pane
CMD + ALT + 0 to zip to close the riht pane