object-c學習筆記:類別的使用(category)

來源:互聯網
上載者:User

如何使用?

這裡只是記錄下如何使用的文法規則,至於類別的優缺點,使用情境,等等細節,sorry。。不知道 yet

基本上你只需要聲明另外一個類,並且指定你需要擴充的類,簡單的,看例子:

代碼

@interface Engine : NSObject
{
}
@end

@implementation Engine

- (NSString*) description
{
return (@"engine");
}

@end

@interface Tier : NSObject
{
}
@end


@implementation Tier

- (NSString*) description
{
return (@"tier");
}

@end

@interface Car : NSObject
{
int tier_num;
float engine_power;
NSString* name;
Engine* engine;
Tier* tier;
}

@property (nonatomic) int tier_num;
@property (nonatomic) float engine_power;
@property (nonatomic, copy) NSString* name;
@property (nonatomic, retain) Engine* engine;
@property (nonatomic, retain) Tier* tier;

@end

@implementation Car

@synthesize tier_num;
@synthesize engine_power;
@synthesize name;
@synthesize engine;
@synthesize tier;

- (id) init
{
if (self = [super init]) {
tier_num = 4;
engine_power = 100;
name = @"BMW";
}
return self;
}
@end

@interface Car (CarCanDescription)

- (void) print;

@end

@implementation Car (CarCanDescription)

- (void) print;
{
NSLog(@"this is a car");
NSLog(@"%@", engine);
NSLog(@"%@", tier);
NSLog(@"engine_power is %f", engine_power);
}

@end


int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Car* car = [[Car alloc] init];
car.name = @"Mazd";

Engine* newEngine = [[Engine alloc] init];
car.engine = newEngine;
Tier* tier = [[Tier alloc] init];
car.tier = tier;
[car print];

// insert code here...

[pool drain];
return 0;
}

 

需要注意的是,當你在定義一個category時,不能指定新的執行個體變數,即使時空的括弧,也會導致編譯不過,道理也很簡單,category只是改變類中函數列表,是不會去改變執行個體變數的,也就無法增加新的變數。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.