about protocols

Apr052010

Protocols declare methods that can be implemented by any class.

  • To declare methods that others are expected to implement

  • To declare the interface to an object while concealing its class

  • To capture similarities among classes that are not hierarchically related


  • Formal Protocols

    @protocol MyProtocol

    - (void)requiredMethod;

    @optional
    - (void)anOptionalMethod;
    - (void)anotherOptionalMethod;

    @required
    - (void)anotherRequiredMethod;

    @end

    Informal Protocols

    @interface NSObject ( MyXMLSupport )
    - initFromXMLRepresentation:(NSXMLElement *)XMLElement;
    - (NSXMLElement *)XMLRepresentation;
    @end

    Adopting a Protocol
    @interface ClassName : ItsSuperclass < protocol list >
    Categories adopt protocols in much the same way:
    @interface ClassName ( CategoryName ) < protocol list >

    @interface Formatter : NSObject < Formatting, Prettifying >
    @end