Introduction to protocols and delegates

 

iOS uses what is called “Protocols” and “Delegates” to communicate between classes.

A protocol is a definition of callbacks that the same class can call on another class.

A delegate is a class that can receive callbacks of a specific protocol.

Let us look at CBCentralManager class as an example :

CBCentralManager has a protocol called “CBCentralManagerDelegate” it has the following callbacks :

optional:
centralManager:didConnectPeripheral:
centralManager:didDisconnectPeripheral:
centralManager:didDiscoverPeripheral:
centralManager:didFailToConnectPeripheral:
centralManager:didRetrieveConnectedPeripherals:
required:
centralManager:didUpdateState:

These are all the possible protocol methods that CBCentralManager can call (you could call them “events”).

I’ll explain these as we use them in our code in the other tutorials, but to demonstrate how a protocol/delegate pair works will look at the two  centralManager:didUpdateStatecentralManager:didConnectPeripheral

 

Here’s how its done :

 

In our header file, there are two things you have to do :

  1. Add import statement for CoreBluetooth framework.
  2. Add the “<CBCentralManagerDelegate>” to your class definition to define that your class obeys the “CBCentralManagerDelegate” protocol.

 

In the your class source files you will need to add the delegate functions needed by you and the protocol you are implementing (as seen in line 12 – 20) , some protocols have methods which are required, these must be implemented in your class or your program will hit an exception !

Add the parts above to your main program, these do :

  1. Init the class you have made
  2. Init the CBCentralManager class with delegate set to the class you wrote and inited.

The CBCentralManager will now be able to call the functions in our class when the events occur.

 

One Response to Introduction to protocols and delegates

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">