Category in iPhone

Difference Between Category & Inheritance

After using inheritance, a derived class can only access those methods that existed in the base class. The derived class can't access the extended method in the category.

BaseClassInheritance-Iphone.png

But after using the category, the derived class can access all the methods (existed + extended) in the derived class.

CategoryIMplementation.png

class myClass.h

@interface test : UIViewController{

}

-(NSString *) method 1;

-(NSString *) method 2;

@end

class myClass.m

@implementation{

-(NSString*) method1{

return( @"method1");

}

-(NSString *)method2{

return (@"method2");

}

}

/////

class yourClass.h

#import "myClass.h" 

@interface{

...

}

class yourClass.m

@implementation{

-(void)viewdidLoad{

myClass * _myclass = [[ myClass alloc]init];

NSLog(@"%@),[_myclass method1]); 

NSLog(@"%@),[_myclass method1]); 

}

}

////////  Category implementation.  (className +categoryName)

Step 1

Choose the Category template from the XCode new file.

category-TemplateSelection.png


Step 2

Category on the name for the super-class.

category-supperclass-in-IPhone.png

#import <Foundation/Foundation.h>

#import "myClass.h"

@interface myClass(ktest)

-(NSString *) method4;

-(NSString *) method5;

@end

#import <Foundation/Foundation.h>

#import "myClass.h"

@interface myClass(ktest)

-(NSString *) method4;

-(NSString *) method5;

@end


//// Category class.m file

#import "myClass+ktest.h"

@implementation myClass(ktest){

-(NSString *) method4{

return (@"method4");

}

-(NSString *) method5{

return (@"method5");

}

/// Category Implementation in your Derived Class

 yourClass.m


#import"myClass.h"

#import "myClass+ktest.h"

@implementation{

-(void)viewdidLoad{

myClass * _myclass = [[ myClass alloc]init];

/**After Importing the "myClass+ktest.h"  same object of _myClass  can implement all the method i.e myClass and  methods from myClass+test **/

NSLog(@"%@),[_myclass method1]); 

NSLog(@"%@),[_myclass method2]); 

NSLog(@"%@),[_myclass method3]); 

NSLog(@"%@),[_myclass method4]); 

}

}


Similar Articles