iOS – Usage of Category

Category

What is Category and why do we need this in iOS Development?

First thing you need to know, Category is not a subclassing (Inheritance). Category is simply a concept of adding methods to your existing class. No need to create the instance of your category class as it will be called from your Main class instance.

Not Getting? Lets take an example….

We have class Car, inside it have methods getCarSpeed, getCarColor.

// Header File
@interface Car : NSObject

-(NSInteger) getCarSpeed;
-(UIColor *) getCarColor;

@end
// Implement File
#import "Car.h"

@implementation Car
-(NSInteger) getCarSpeed
{
return 100;
}
-(UIColor *) getCarColor
{
return [UIColor greenColor];
}
@end

//Now I need to create one category class where I am adding one method.

#import <Foundation/Foundation.h>
#import "Car.h"

@interface Car (Modified) //This is the Category

-(NSInteger) getCarMileage;

@end

#import "Car+Modified.h"

@implementation Car (Modified)

-(NSInteger) getCarMileage
{
return 12;
}

@end

We have created a Category of Car Class.

Now let us call it from UIViewController.

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
Car *car = [[Car alloc]init]; //We are creating an instance of Car only
NSInteger milage = [car getCarMilage];
}

If you notice here we have created the instance of the Car but we are calling the method of Car+Modified.

Try it with your self for better understanding.

Adding methods in existing Class NSString

// Header File
#import <Foundation/Foundation.h>
@interface NSString (MyString)
-(NSString *) reverseString;
@end

// Implementation File
#import "NSString+MyString.h"
@implementation NSString (MyString)
-(NSString *) reverseString
{
NSMutableString *reversedString;
NSInteger strLength = [self length];
reversedString = [NSMutableString stringWithCapacity:strLength];

while (strLength > 0)
{
[reversedString appendString:[NSString stringWithFormat:@"%C", [self characterAtIndex:--strLength]]];
}

return reversedString;
}
@end

Here we have added the ‘reverseString’ method to existing NSStirng Class. Now this method is available for use along with other methods of the NSSting.

Scenarios / Situations were we use Category

– Split the code according to the module (For each module go for different category)
– Add methods to iOS SDK classes Like NSString, UIColor, UIFont (Frequently used)

Leave a Reply