An Introduction to Categories in Objective-C
Categories are parts of a class that have been separated out in order to keep the class specific & compact while providing additional functionality.
A category is made by taking related methods and properties (that maybe slightly tangential to the main purpose of the class) and putting them into a separate category file. The main class stays concise and the contents of the category can still be used with the class easily.
Categories can add new functionality to a class after its creation.
Categories make it easy to include or exclude parts of the class by choosing to include only the categories you need at a particular moment.
To make a category, let’s use the example of a Dinner class.
A Dinner class could contain properties like an appetizer, mainDish, & numberOfPlates, and methods like prepareAppetizer: or setTable.
The implementation for the Dinner class would be:
The properties and methods seem to cover all we need for preparing and serving a dinner, but what happens if later on we need to clean up and do dishes??
We still want to take into account the same water glasses, dishes, silverware and napkins in the class, but we want to add the new functionality.
We should also take into consideration that we might not always need to do the dishes after every dinner(it might be someone else’s turn!), so using a category can be useful for omitting this functionality without disturbing the original class.
Making a Category is simple.
- Now that the Dinner class files are created. Add a new file to the project.
- Choose Objective-C file. (At the bottom of the page it states “An empty Objective-C file, category, protocol, or extension.” This is the one you want.)
3.Give the category a name, like CleanUp. And make sure the class is the correct class name.
4. A new pair of interface(.h) & implementation(.m) files will be created. The file names will look like this: Dinner+CleanUp.h Dinner+CleanUp.m. Notice the + between the original class name and the new category file name.
5. Open the files and add the new methods for the CleanUp class, just as you would for a new class. Notice the new way that the category name is specified without : and surrounded by ( ).
6. The category is ready to be used! Just remember to import it in addition to the original class file where ever you want to use it.
Keep in mind when using categories:
You shouldn’t use a category to override existing methods in a base class. Categories are not subclasses so if you try to override again with another category the compiler will not know which instructions to follow.
Have you ever wished you could add a method to an existing class that you don't have the code for? Well, now you can…www.ios-blog.co.uk