分類機制允許向一個類檔案中添加新的方法聲明,它不需要使用子類機制,並且在類實現的檔案中的同一個名字下定義這些方法。
#import “ClassName.h”
@interface ClassName (CategoryName)
@end
Vector.h 代碼
#import <Foundation/Foundation.h>
@interface Vector : NSObject
{
double _vec1;
double _vec2;
}
@property (nonatomic,assign) double vec1;
@property (nonatomic,assign) double vec2;
-(Vector *)add:(Vector *)v;
-(void)setVec1:(double)vec1 AndVec2:(double)vec2;
-(void)print;
@end
Vector.m 代碼
#import "Vector.h"
@implementation Vector
@synthesize vec1=_vec1;
@synthesize vec2=_vec2;
-(void)print
{
NSLog(@"v1 value is %f,v2 value is %f",self.vec1,self.vec2);
}
-(void)setVec1:(double)vec1 AndVec2:(double)vec2
{
self.vec1=vec1;
self.vec2=vec2;
}
-(Vector*)add:(Vector *)v
{
Vector *vector=[[Vector alloc]init];
vector.vec1=v.vec1+self.vec1;
vector.vec2=v.vec2+self.vec2;
return vector;
}
@end
vector+sub.h 代碼
#import <Foundation/Foundation.h>
#import "Vector.h"
@interface Vector(sub)
-(Vector *)sub:(Vector *)v;
@end
vector+sub.m code
#import "Vector+sub.h"
@implementation Vector (sub)
-(Vector *)sub:(Vector *)v
{
Vector *temp=[[Vector alloc ]init];
temp.vec1=self.vec1-v.vec1;
temp.vec2=self.vec2-v.vec2;
return temp;
}
@end
main code:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Vector *test1=[[Vector alloc]init];
[test1 setVec1:2.2 AndVec2:3.4];
[test1 print];
Vector *test2=[[Vector alloc]init];
[test2 setVec1:1.1 AndVec2:1.2];
Vector *ret=[test1 sub:test2];
[ret print];
[test1 release];
[test2 release];
}
return 0;
}
result:
2013-05-06 17:38:34.751 Access[2057:303] v1 value is 2.200000,v2 value is 3.400000
2013-05-06 17:38:34.753 Access[2057:303] v1 value is 1.100000,v2 value is 2.200000
分類是C++沒有的概念,分類的使用是通過Objective-C的動態綁定實現,通過分類能夠實現比繼承更好的效果