Search code examples
ioscocoadelegation

How does Apple dictate which classes should be broken out to a protocol interface for a class?


I'm continuously wrapping my head around what exactly the term delegate means by doing numerous apps using UITableView and NSSpeechSynthesizer. I've read some helpful blogs and books so it seems to come down to being a design pattern that fulfills single responsibility or separation of concerns (or at least thats my opinion). My question is, does anyone know the point of which Apple decides to use delegate composition for classes?


Solution

  • Forget about design patterns. If there is a design pattern, then it's the "delegate design pattern".

    A UITableView can display data in a gazillion different ways. And the data can come from a gazillion different places. A UITableView cannot handle all that.

    That's why the application supplies one delegate object that provides the data for the UITableView. The delegate must be able to tell the UITableView how many sections there are in the table, how many rows in each section, the data for each row, the header and footer for each section. With that knowledge, the UITableView can do its job. Without this delegate, you'd have to create lots and lots of subclasses of UITableView, which is a pain.

    But there is no UITableViewDelegate class, because then you would have to create lots of subclasses of UITableViewDelegate, and have exactly the same problem of gazillions of subclasses. Instead there is a protocol. The protocol defines which methods the delegate needs to support, and then you add those delegate methods to some class that understands the data anyway.

    So how the delegate pattern works: You create a class that does that hard work. But in order that the class can adapt to different situations, you supply it with a delegate object which implements the differences between different situations. The delegate object is usually an instance of a completely unrelated class, to which the delegate methods have been added.