Objective-C – Delegates and Protocols

The delegate design pattern creates a system wherein one object passes work to another object. The first object stores a reference to another object, it’s delegate, and calls methods in the delegate object.

To make this system work there are two problems to solve. First. the main class needs a reference to the delegate object. The second problem is the need for the delegate object to implement the methods the delegator object will invoke. Without this guarantee your program runs the risk of no working or crashing.

The first problem is easily solved by adding a property to the delegator that holds a reference to it’s delegate object.

The second problem is solved by declaring a protocol. A protocol declares methods and properties that an object will invoke in it’s delegate. Any class that will act as a delegate implements the protocol, and the methods the defined in the protocol.

When the compiler sees a class that implements a protocol, it checks that the methods declared in the protocol are defined in that class. If not you get a warning or an error.

Declare a protocol in the header file above of @interface with:

@protocol ProtcolName <Class>
-(void)aMethod;
@end

Declare a delegate property to hold an object that implements the protocol. The delegate property should be weak to avoid dependancies!

@property (weak, nonatomic) id <ProtcolName> delegate;

Use the id type here since the delegate object could be of any type.

 

Leave a Reply

Your email address will not be published. Required fields are marked *