chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Protocol in Objective-C

2015-01-25

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 protocol option:

http://www.arkilis.me/wp-content/uploads/2017/04/WX20170425-135206.png

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.

http://www.arkilis.me/wp-content/uploads/2017/04/WX20170425-135312.png

Step 3: In the MyProtocol.h

Notice:
@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

Notice:
If you didn't implement the above methods, you will receive warnings instead of errors.

http://www.arkilis.me/wp-content/uploads/2017/04/WX20170425-140736.png

Reference

https://useyourloaf.com/blog/quick-guide-to-swift-delegates/

arkilis

Make Your Comments