It's named as Categories. Shortly if you already have a class declared in a header file, let's say in file myclass.h, and the class implementation is in myclass.cpp file, you may add new methods to this class declared and implemented in other files. It is possible to new methods even for the classes from the Foundation framework.
I added methods to the class Fraction I used in my previous posts. Here is MathOp.h file:
#import "Fraction.h"And here is MathOp.m:
@interface Fraction (MathOp)
-(void) add: (Fraction*) fraction;
-(void) substruct: (Fraction*) fraction;
@end
#import "MathOp.h"This is a program written to test this class:
@implementation Fraction (MathOp)
-(void)add: (Fraction*) fraction
{
numerator = numerator * fraction.denominator + fraction.numerator * denominator;
denominator = denominator * fraction.denominator;
[self reduce];
}
-(void) substruct: (Fraction*) fraction
{
numerator = numerator * fraction.denominator - fraction.numerator * denominator;
denominator = denominator * fraction.denominator;
}
@end
#import <Foundation/Foundation.h>And it works fine:
#import "Fraction.h"
#import "MathOp.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *fraction1 = [[Fraction alloc] initWith: 1 : 2];
Fraction *fraction2 = [[Fraction alloc] initWith: 1 : 3];
[fraction1 substruct: fraction2];
[fraction1 print];
[fraction1 release];
[fraction2 release];
[pool drain];
return 0;
}
It is impossible to add an instance variable, but this way allows to add new methods and override the existing ones. In the last case, there is no access to the original method. It is applied to all classes derived from the modifying one.
You may have as many categories as you wish. The name of the category must be unique. If a method is defined in more than one category, the language does not specify which one will be used.
No comments:
Post a Comment