When you want to add something to the existing class normally we go for subclassing.In Objective we can new method to the existing class and the term called as "Category".
Suppose in Circle class u want to add method for converting radius from float to int (let say some extra rounding off). The declaration of category as
.h file
It much look like class declaration.
Here category name is Conversion. You can not add instance variable to existing classes by category.
.m file
Categories are used for adding informal protocols to an object.
Suppose in Circle class u want to add method for converting radius from float to int (let say some extra rounding off). The declaration of category as
.h file
@interface Circle (Conversion) // existing name + new name in parenthesis
- (int *) floattoint;
@end
It much look like class declaration.
Here category name is Conversion. You can not add instance variable to existing classes by category.
.m file
@implementation Circle (Conversion)
- (int *) floattoint
{
//here code for conversion+ return value. You can access method of circle class with self.
}
@end
In category if u have same function name as existing class then in that case category function wins and every time that will be get called.
categories are used for to split the single class into multiple file. In objective C its not possible to have single class in multiple .m files.
Example
1.Maincalss
.h file
@interface MainCategory
{
int temp1;
int temp2;
}
@end
,m file
@implementation MainCategory
//write if u want any function
@end
2.1st category class
h file
@interface MainCategory (Category1)
-(void) settemp1 :(int) t;
@end
,m file
@implementation MainCategory (Category1)
-(void) settemp1:(int) t
{
temp1=t;
}
@end
3.2nd category class
h file
@interface MainCategory (Category2)
-(void) settemp2 :(int) t;
@end
,m file
@implementation MainCategory (Category2)
-(void) settemp2:(int) t
{
temp2=t;
}
@end
main function
int main (int argc, const char *argv[])
{
MainCategory *maincat;
maincat = [[MainCategory alloc] init];
[maincat settemp1: 34];
[maincat settemp2: 24];
[thing release];
return (0);
}
Category are used for forward declaration.
You can implement method in main class without declaring it in @interface. If you want to use same method out side the class better to write new category and in that category @interface declare that method and implementation part of that category will not have anything.
Categories are used for adding informal protocols to an object.
0 comments:
Post a Comment