Objective-C provides a feature for defining the new methods for an existing class even for the class whose source code is not available to you. One can make use of categories when their is a need to add new methods to the predefined classes such as COCOA classes-‘NSString etc.’ without sub-classing it .

A category is a group of methods for a class which are available to all through the class and can be used as the methods declared in the interface of the method. This helps to split up the class having numbers of methods in to several interface and implementation files, which helps in maintaining the large projects.The category name indicates that the methods are the additions for the class defined earlier and not a new class.

Consider a class ‘car’

// car.h

#import <Foundation/Foundation.h>

@interface Car : NSObject

-(void)startEngine;

-(void)applyBreak;

@end

Now consider the above ‘car’ class for which we want to add some new methods/capabilities (maintenance),we can do this by using categories as below.

// car+Maintenance.h

#import “car.h”

@interface Car (Maintenance)

-(void)maintainanceTyre;

-(void)maintainanceEngine;

@end

The implementation file for this category ‘maintenance’ would be as below:

// Car+Maintenance.m

#import Car+Maintenance.h

@implementation Car (Maintenance)

-(void)maintainanceTyre                                 //method 1 defination

{

}

-(void)maintainanceEngine                                 //method 2defination

{

}

@end

Now the methods ‘-(void)maintenanceTyre’  &  ‘-(void)maintenanceEngine’  will be available to all the objects of the ‘car‘ class.

#import <UIKit/UIKit.h>

#import Car.h

#import Car+Maintenance.h”                                      //category 

int main(int argc, char * argv[]){

@autoreleasepool {

Car *car1 = [[Car alloc] init];

//using methods from the class ‘car’

[car1 startEngine];

[car1 applyBreak];

//using additional methods from the category maintenance for the car1 object

[car1 maintenanceTyre];

[car1 maintenanceTyre];

}

}

Download : Sample XCode project on categories and extension Here!