简体   繁体   中英

What is a Protocol?

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM