A protocol is a group of related properties and methods that can be implemented by any class. They are more flexible than a normal class interface, since they let you reuse a single API declaration in completely unrelated classes. This makes it possible to represent horizontal relationships on top of an existing class hierarchy.
Which you can understand as, in the normal class inheritance, class and subclass are in the vertical relationship. While a protocol can:
- Create a class in the same level
- Allow many other classes ~~implement~~ adapt the same protocol
- Guarantee the other classes to adapt all the methods
Here is one example of creating a protocol in Objective-C:
Step 1: create an Objective-C file and select a the
Step 2: Give a protocol a name, i.e.
MyProtocol in this case, choose
Protocol in the File type. There is one issue here with Xcode, as you might observe a different name in the class drop downbox, which is in grey color. However, the value is not changeable. Actually we don't need to specify a class here.
Step 3: In the MyProtocol.h
@required is not quite necessary as it is required by default. Also you can use
@optional here to tell those method may not be implemented in the adapted classes.
Step 4: In the viewcontroller
If you didn't implement the above methods, you will receive warnings instead of errors.