Search code examples
iosdelegatesprotocols

What exactly are protocols and delegates and how are they used in IOS?


I'm really confused about the concept of delegates and protocols. Are they equivalent of interfaces and adapter classes in Java? How do they work? None of the resources I've read were helpful so far. "Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it." I have no idea what this means. Can someone please explain what they are and give a simple example? Thanks in advance!

EDIT:

As far as I now understand,

1) delegates implement protocols (another name for interfaces)

2) object registers a delegate (that implements a protocol)

3) object can call protocol methods on the delegate

Therefore, a delegate is connecting the object with the protocol.

Please correct me if I'm wrong.

I still don't understand why the object itself can't implement a protocol? It could've been so much easier!


Solution

  • Protocols are a way to specify a set of methods you want a class to implement if it wants to work with one of your classes. Delegates and Data Sources like UITableViewDelegate and UITableViewDataSource are protocols indeed.

    You specify a protocol this way:

    @protocol MyProtocol <NSObject>
    
    - (void)aRequiredMethod;
    
    @required
    - (void)anotherRequiredMethod;
    
    @optional
    - (void)anOptionalMethod;
    
    @end
    

    Methods declared after the @required or before any other specifier are required and the classes that want to use your protocol need to implement all of them. You can also declare some optional methods by declaring them after the @optional specifier.

    You then can specify that a class "conforms" to a protocol (implements the required methods) in the interface of the class:

    @interface MyClass <MyProtocol>
    
    @end
    

    You usually keep a reference to an object conforming to a protocol using a property. For example, to keep track of a delegate:

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

    At this point, in your code, you just have to call the method you want to call on the object that you're keeping reference of and that implements your protocol as you would with any other method:

    [self.delegate aRequiredMethod];
    

    To check whether an object conforms to a protocol you can call

    [self.delegate conformsToProtocol:@protocol(MyProtocol)]
    

    To check whether an object implements a method you can call

    [self.delegate respondsToSelector:@selector(anOptionalMethod)]
    

    For more information, check the Apple's guide Working With Protocols.