Categories

In Objective-C, classes have instance and class methods. These define the behavior of a class and its instances. Sometimes, you are using a class and you really wish it just had a method to do this cool thing I want to do. You’re in luck. You can add methods to an existing class by creating a category for that class.

The syntax for a category is not at all scary like blocks; in fact, it’s something you’ve already used before. You will create a category for UIColor that has two new methods that an instance of UIColor will respond to. Create a new NSObject subclass. Name it UIColor+Extract.m. In UIColor+Extract.h, replace all of the code with the following:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​
 #​i​m​p​o​r​t​ ...

Get iOS Programming: The Big Nerd Ranch Guide, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.