Wednesday, November 21, 2012

objective c categories

Categories is another good feature in ObjectiveC. A category  is used to add the new methods to the existing class, even if you don't have source code of the class. Category only adds methods and not variables. The basic difference between category and extending the class is that, in extending the class you can additional methods and variables. But in category only methods are allowed.

A category is also used to declare the private methods. ObjectiveC provides security to only data variables and not for methods. So we can have public, protect and private access privileges to only data.  Using category we can implement private methods. But we need to declare the methods in .m file and not in .h file.

Key points on Category:
  • Used to add the new methods to the exiting class and not variables
  • Used to create the private methods in objectiveC
  • No keyword is used for declaring category. Only enclosed in braces(see the syntax).
  • You can take as many catefories as you want, but they should be unique.
Syntax for the Category:  There is no keyword for the declaration of the category. We need to enclose in the braces '(' and ')';
//.h file
@interface className (categoryName)
//new methods
//.m file
@implementation className (categoryName)
//new method definitions

Example for adding methods: In this example we add display method to the NSObject. We we have written two implementations, one is for NSObject new method and one is for new class.

// this is .h file
@interface NSObject (print)
-(void) display;

@interface categoryClass : NSObject


//this is in .m file

@implementation NSObject (print)
-(void) display
    NSLog(@"this is display function");

@implementation categoryClass

int main()
    categoryClass *obj = [[categoryClass alloc] init];
    [obj display];

Popular Posts