Hello!
Today we will be learning about categories and protocols. First though, download the starter project here.
Today we will be learning about categories and protocols. First though, download the starter project here.
Categories
First up are categories. Categories are a list of methods that have been declared and implemented that can be used on objects. You create a category that corresponds with a certain class. That class and subclasses of that class can use the methods that were declared in the category. So open up the starter project. Don't worry about all of the errors they will soon be solved. There are errors because in ViewController.m we are calling methods that do not exist. They will be implemented when we create the category. So first create a new file.
Then choose Objective-C category.
Name it like this.
And after pressing next keep the bottom part like this.
Then press create! You will notice the two new files have the name that we put in Category on (Calculator) and then the name of the Category we set (SetTheNumber) to be Calculator+SetTheNumber. Now declare the method in the Calculator+SetTheNumber.h file.
Then implement it in the .m file.
Then go to the ViewController.m file and import the category. You should then see the error go away.
Run the project and look at the debug area!
It worked!
Protocols
Now go to the ViewController.m file and comment out the last method call and uncomment the next four. Once again ignore the errors.
Now we are going to create a protocol! Create a new file.
Choose Objective-C protocol.
Name it Operations.
Keep the bottom like this.
Then Create! Notice how only a .h file is created. This is because n protocols you only declare methods that the class will use. You do not make the methods do anything. Now go to your Operations.h file. declare these four methods.
Now we are going to use this protocol inside the Calculator class. Go to the Calculator.h file. Write this code in. The import statement at the top allows us to include the protocol with these <>.
Now if we include the protocol inside a class then we must use those methods we just declared inside the class. If we don't we get a warning.
Now make those methods do something inside the Calculator.m file.
Now run the project!
Wow! Nice job! We are drawing to a close for this Objective-C tutorial series. We have one more content-based post next on blocks! As always feel free to post any comments, suggestions, or questions down below or at [email protected].
Thank You!
Zachary Cmiel
The PoKoBros
Thank You!
Zachary Cmiel
The PoKoBros