Pages

Monday, December 28, 2009

Objective-C. Categories

It is an absolutely new for me. I've never seen such thing in C, C++ or C#. I even do not know if it is good or bad. From other side, I do not understand why it is not implemented in other C++ compilers.

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"

@interface Fraction (MathOp)
-(void) add: (Fraction*) fraction;
-(void) substruct: (Fraction*) fraction;

@end
And here is MathOp.m:
#import "MathOp.h"


@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
This is a program written to test this class:
#import <Foundation/Foundation.h>
#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;
}
And it works fine:



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