Helpers was one of the ways we did callbacks last semester.
Remember we mentioned that one form of helper had one object and several methods? We also said that the methods in the helper object were just magically known?
We did this with the NSURLConnection class. Here are some of the methods that it called for us.
Well, sorry to say this, but there’s no magic. It’s done with Protocols.
What’s a protocol? It’s really simple, it’s just a list of methods and their parameters. Here’s a simple example.
We create a protocol by creating a new file. However, we make a protocol file instead of a class file.
Here’s the code that is created. The first thing that’s different is that we only get a .h file.
Then it’s a @protocol, not an @interface.
Now we’ll add a method declaration.
And, we’re done. That’s a Protocol. What?
That’s right, a protocol is just a list of methods, there is no code other than the method declaration. It’s just a way for us to tell a class what methods are needed.
So, what’s the point?
Using a Protocol
The way we use a protocol is in other classes.
Here’s a simple class’s .h file.
Now we’ll add the code so we can use the protocol.
First, we have to import the .h file
Then we add <SampleProtocol> at the end of the class declaration.
So, what does that do for us?
Let’s get a hint by building our application. Just press ⌘-B. And we get this:
When we add <SampleProtocol> to a class declaration we are conforming to a Protocol. That is, we are promising the compiler that we will have the methods that are listed in the protocol file.
The compiler sees that we have promised to have a method named aShinyMethod and we don’t have it. Let’s add it. Switch to the .m file of our class and implement the method.
When we build the class again, the warning goes away, the compiler is happy!
You might still be wondering about the point of this. How’d you guess?
The next step in the demo is to make another class that also conforms to the protocol. Here’s the .h.
And the .m
Now we get to see the point in the main function. Here’s the code in the main.m file.
We start by importing the files we need. Notice that we don’t import the protocol file.
Next, we create an instance of each of the classes. Remember that these classes are not related to each other. They are completely independent. They just both conform to the same protocol.
Now we make an array with these two objects.
And now for the magic! We’re going to loop through these two objects and call the aShinyMethod on each of them. How can we do that? They aren’t the same class so how can we declare a variable that will hold either of them? Here’s the answer.
They both conform to the same protocol. Conforming to a protocol means that you added a type to your class. The two objects are the same type, the SampleProtocol type. This is how we declare a variable of the type of the protocol.