object-c学习笔记:类别的使用(category)

如何使用?

这里只是记录下如何使用的语法规则,至于类别的优缺点,使用场景,等等细节,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只是改变类中函数列表,是不会去改变实例变量的,也就无法增加新的变量。

 

posted @ 2011-01-19 09:30  hjtc  Views(2093)  Comments(0Edit  收藏  举报