Home Iphone Objectivec Categories



Categories
Posted on: September 26, 2008 at 12:00 AM
When programmer wants to add some more functionality to the class, typically extend the class.

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

Related Tags for Categories:
crubyobjective-cideclassantfunctionobjectfunioclassesvireadthisidfunctionalprogrammerlikeiecalluncaddwherewithprogramtoramicalextendssepicwsextcategorieseitdesnotlsliinnoextendingcalasmntoutwansticaddjadcleswithoutemfuncendallpimeobjobjectiveprocatrightwhenssoatkisllivgoeafunctionalityexistingxtwantxissrithstchiantsexiendinglsojeicaicaprndonomogro


More Tutorials from this section

Ask Questions?    Discuss: Categories   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.