objective-C中分類的實現

來源:互聯網
上載者:User

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

#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的動態綁定實現,通過分類能夠實現比繼承更好的效果

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.