One thing I really love about Objective-C is Categories.
What are they?
Categories make it possible to add a method to a class without subclassing.
Let’s assume that you want to create a method
isEmpty. And you want to find a clean way to ask the NSString instance for it.
Then we’ll create a category on the NSString class in which we define a method
isEmpty that returns a BOOL value.
How to create them?
Create a header
(NSString+UtilityMethods.h) and an implementation file
You define the category and the method in the header file like this:
And in the implementation file like this:
Now you can use the
isEmpty method on every instance of NSString. (Don’t forget to include the
The above snippet will print out “Categories are awesome”.
Another example with UIColor
This is how I clean up my code with categories. I create a category on UIColor to add methods that return every different UIColor used in my application. This way I only have to modify the colors here in orde to change them in the app.
Nice isn’t it?
Sign up for our newsletter
Who’s got the mic?
Architecture & Design
Koen Van Der Auwera
Bob Van Landuyt
Nathan de Witte