cocoacocoa-touchdesign-patternsswift-protocolsobjective-c-protocol

What is the purpose of protocols if all methods are optional?


I understand what purpose protocols serve (to have a type conform to a set list of methods or/and properties), but I don't understand what the purpose is of a protocol with all optional methods. One example would be UITextFieldDelegate.

If all methods are optional in a protocol, why would you conform to the protocol instead of just writing the methods from scratch in your class? I don't see what the benefit or purpose of conforming to the protocol is in this case.

Are the optional methods there just as suggestions of functionality that could be implemented?


Solution

  • Historically, for delegates and data sources in Cocoa, informal protocols were used. Informal protocol was implemented trough a category for NSObject class:

    @interface NSObject (NSTableViewDelegate)
    
    - (int)numberOfRowsInTableView:(NSTableView *)tableView;
    
    // ...
    
    @end
    

    Later, optional methods in protocols were introduced. This change leads to better documenting of class responsibilities. If you see in code, that class conforms to NSTableViewDelegate, you suspect that somewhere exists a table view, that managed by instance of this class.

    Also, this change leads to stronger checks in compile time. If programmer accidentally assign wrong object to delegate or dataSource properties, compiler will warn.

    But your assumption is also correct. Optional methods are also suggestions for possible functionality.