What is a Protocol?
Asked Answered
W

2

9

I've read the documentation but I'm still confused. Can someone please explain what a protocol is? (You could give code examples but I'm really looking for an explanation)

Wintry answered 20/10, 2010 at 20:6 Comment(0)
A
11

Here's a great article on it. Effectively, a protocol in Objective-C is very similar to an interface in Java or a pure virtual class in C++ (although not exactly as pure virtual classes can have data members...). It's basically a guarantee that a specific class knows how to respond to a given set of methods (messages).

Edit The original article disappeared so I have replaced it with a different tutorial.

Apoloniaapolune answered 20/10, 2010 at 20:9 Comment(2)
It's a guarantee unless the protocol defines optional methods. In that case you still have to check if the method is implemented or not.Thermodynamic
protocol can also have properties.Counterpunch
E
4

A protocol is means to define a list of required and/or optional methods that a class implements. If a class adopts a protocol, it must implement all required methods in the protocols it adopts. Cocoa uses protocols to support interprocess communication through Objective-C messages. In addition, since Objective-C does not support multiple inheritance, you can achieve similar functionality with protocols, as a class can adopt more than one protocol.

A good example of a protocol is NSCoding, which has two required methods that a class must implement. This protocol is used to enable classes to be encoded and decoded, that is, archiving of objects by writing to permanent storage.

   @protocol NSCoding

     -(void)encodeWithCoder:(NSCoder *)aCoder;

     -(id)initWithCoder:(NSCoder *)aDecoder;

   @end

To adopt a protocol, enclose the name of the protocol in <> like below

   @interface SomeClass : NSObject <NSCoding> 

    {
     some variables
    }

How to define a Protocol?

We can create both required an optional methods within a protocol. What follows is a definion of a protocol named 'Hello':

   @protocol Hello
    - (BOOL)send:(id)data;
    - (id)received;
   @optional
    - (int)progress;
   @end

To use the protocol, as with the example above, declare the protocol in the interface and write the required methods in the class implementation:

// Interface @interface AnotherClass : NSObject

   {
    some declaration
   }

// Implementation @implementation AnotherClass

  - (BOOL)send:(id)data
   {
    some declaration
   }

  - (id)received
   {
    some code
   }

// Optional method

  - (int)progress
   {
    some code 
   }
   @end

I hope it helps you to learn Protocol.

Empower answered 4/5, 2012 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.