[an error occurred while processing this directive]



When programmer wants to add some more functionality to the class, typically extend the class. But this is not a right way everywhere, so like ruby Objective-C also provides categories to achieve this. Categories allows programmer to add functionality to already existing classes without extending them.

In the example given below we have a class BaseClass that has some methods and the second class SubClass that is used to add a method to the BaseClass. In the main, we have created object of base class and use the method defined in the sub class.

This is code of primary class.

BaseClass.h BaseClass.m
@interface BaseClass : NSObject {
    int num1, num2;
  -(void)set :(int) x and: (int) y;



@implementation BaseClass
    -(void)set :(int) x and: (int) y {
        num1 = x;
        num2 = y;
    -(int)add {
        return num1+num2;
    -(int)sub {
            return num1-num2;
            return num2-num1;

This is code of sub class that is used to add method in the primary class.

SubClass.h SubClass.m
@interface BaseClass(Category)


@implementation BaseClass(BaseClass)
  -(void)show:(int)x {
      printf("Result is : %d \n",x);








int main(){
   BaseClass *obj = [[BaseClass alloc] init];
   [obj set:10 and:8];
   [obj show:[obj add]];
   [obj show:[obj sub]];
   [obj release];
   return 0;


Result is : 18 
Result is : 2 

Download Source Code


[an error occurred while processing this directive]