How to define a Protocol in Objective-C

Protocols are a great way to delegate responsibility from one class to another.

Consider a view controller that brings up another view controller via a modal segue. Let’s call them ViewController and DetailViewController. When it comes to dismissing that DetailViewController, he could do it himself via

However, the first ViewController wouldn’t be in charge of that process. If we wanted to make that happen, we can define a protocol on DetailViewController, then have ViewController conform to it and hence be in charge of the dismissal.

Let’s make it happen!

Defining the Protocol

Most of the work happens in the header file of DetailViewController:

Right after the import statement, we say “we’ll define a protocol in here”. Next we setup a weak property called delegate so that we can declare a delegate elsewhere (other than self).

After the first @end statement we define one method that the delegate must conform to. By default, all methods we define are “required” by the delegate – if we don’t implement them all, then we’ll get a yellow warning mark in Xcode.

We don’t have to define these methods in the implementation file. Instead, we would define where we would like our delegate to execute them. I have one method which will get called when a button on DetailViewController is pressed:

All we do here is say “yo delegate, call my dismiss method and do in it whatever you like”.

Conforming to the protocol

We’ve done this countless times with built-in classes, and the process is exactly the same for our own protocols:

– add the delegate protocol in to ViewController’s header file
– implement the methods in the implementation file

Here’s the very simple ViewController.h header file (ie “the guy who’s in charge”):

And in the implementation file we’d define our only delegate method:

The only remaining thing is to tell DetailViewController who the delegate is. In case of a modal segue like ours this can be done in the prepareForSegue:sender method:

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.