歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Objective-C中分類的實現

Objective-C分類機制允許向一個類文件中添加新的方法聲明,它不需要使用子類機制,並且在類實現的文件中的同一個名字下定義這些方法。

#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

Copyright © Linux教程網 All Rights Reserved