Objective-C: Categories

Objective-C supports extensions of classes using categories. Class categories are defined similar as the class itself. The example defines a class MyClass. The header file declares variables myString and myInt, and methods setMyString and setMyInt.


MyClass.h:

@interface MyClass : ParentClass
{
NSString *myString;
int myInt;
}

– (void) setMyString: (NSString*) str;

– (void) setMyInt: (int) i;

@end


Methods are defined in the class implementation, source file MyClass.m. They are used simply to set the values of the class variables – myString and myInt.

MyClass.m:

#import “MyClass.h”

@implementation MyClass;

– (void) setMyString: (NSString*) str
{
myString = str;
}

– (void) setMyInt: (int) i
{
myInt = i;
}

@end

Class categories are defined similarly to the class itself. In the category class, it is necessary to import the header file of the class that is extended by this category. Then, as the definition of the class, the keyword @interface with the name of the class in parentheses following the name of the category is added.

CategoryOfMyClass.h:

#import “MyClass.h”

@interface MyClass (CategoryOfMyClass)

– (NSString*) categoryMethod;

@end

Category source file is defined similarly to the source file of the class. It is necessary to import the category header file, followed by the keyword @implementation, the class name and the category name in parentheses. Further the category methods are defined as they were methods of the class.

CategoryOfMyClass.m:

#import “CategoryOfMyClass.h”

@implementation MyClass (CategoryOfMyClass)

– (NSString*) categoryMethod
{
return @”Method within the category is called!”;
}

@end

To create an instance of the class MyClass in some other class, the header file of the MyClass has to be imported first, as well as the header file of the CategoryOfMyClass.

#import “MyClass.h”
#import “CategoryOfMyClass.h”

Let the instance of a class MyClass have a name instanceOfMyClass. Declared methods could be called in the following way:

[ instanceOfMyClass setMyString:@”Some string.”];

// the value of myString = “Some string.”
[ instanceOfMyClass setMyInt:123];

// the value of myInt = 123
NSString *someString = [instanceOfMyClass categoryMethod];

// the value of someString is set by a method categoryMethod which is declared and implemented in the category categoryOfMyClass; the value of nekiString = “Method within the category is called!”