Categories

When programmer wants to add some more functionality to the class, typically extend the class.

Categories

Categories

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.

Example:
This is code of primary class.

BaseClass.h BaseClass.m
#import<Foundation/NSObject.h>
@interface BaseClass : NSObject {
    int num1, num2;
  }
  -(void)set :(int) x and: (int) y;
  -(int)add;
  -(int)sub;
@end

 

#import"BaseClass.h"

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

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

SubClass.h SubClass.m
#import"BaseClass.h"
@interface BaseClass(Category)
  -(void)show:(int)x;
@end

 

#import"SubClass.h"
@implementation BaseClass(BaseClass)
  -(void)show:(int)x {
      printf("Result is : %d \n",x);
  }
@end

 


main.m

#import"BaseClass.m"
#import"SubClass.m"
#import<stdio.h>
int main(){
   BaseClass *obj = [[BaseClass alloc] init];
   [obj set:10 and:8];
   [obj show:[obj add]];
   [obj show:[obj sub]];
   [obj release];
   return 0;
}

Output:

Result is : 18 
Result is : 2 

Download Source Code