Objc中的Category

objective-c中对一个类的扩展除了使用常见的继承外还提供了一种独特的方法:分类(Category)。

先看一个使用分类扩展类的小例子:

将被扩展的类:

#import <Foundation/Foundation.h>

@interface Fraction : NSObject
{
    int numerator;
    int denominator;
}
@property int numerator, denominator;
-(void) setTo: (int)n over: (int)d;
-(void) print;
@end

@implementation Fraction
-(void) setTo:(int)n over:(int)d
{
    numerator = n;
    denominator = d;
}
-(void) print
{
    NSLog(@"%d / %d", numerator, denominator);
}
@end

使用obj-c的分类语法扩展Fraction类:

#import <Foundation/Foundation.h>
#import "Fraction.h"

@interface Fraction (MathOps)
-(Fraction*) add: (Fraction*)f;
-(Fraction*) mul: (Fraction*)f;
-(Fraction*) sub: (Fraction*)f;
-(Fraction*) div: (Fraction*)f;
@end

@implementation Fraction (MathOps)
-(Fraction*) add:(Fraction *)f
{
    Fraction *result = [[Fraction alloc]init];
    int resultNum, resultDenom;
    resultNum = (numerator * f->denominator) + (denominator * f->numerator);
    resultDenom = denominator * f->denominator;
    [result setTo:resultNum over:resultDenom];
    return result;
}
@end

分类的特点: