定义扩展的语法如下:
@interface class ()
@end
扩展用于临时对已有类的接口进行扩展。扩展与类别的不同是可以额外追加实例变量。
例:
#import <Foundation/Foundation.h>
@interface APPLECar : NSObject
@property (nonatomic,copy) NSString* brand;
@property (nonatomic,copy) NSString* model;
-(void) drive;
@end
//对APPLECar扩展
#import "APPLECar.h"
@interface APPLECar ()
@property (nonatomic,copy) NSString* color;
-(void)drive:(NSString*)owner;
@end
//类实现部分
#import "APPLECar+drive.h"
@implementation APPLECar
@synthesize brand;
@synthesize model;
@synthesize color;
-(void)drive
{
NSLog(@"%@ are on the road running",self);
}
-(void)drive:(NSString*)owner
{
NSLog(@"%@ driving the %@ car on the road",owner,self);
}
-(NSString*)description
{
return [NSString stringWithFormat:@"brand=%@,model=%@,color=%@",self.brand,self.model,self.color];
}
@end
#import "APPLECar+drive.h"
int main(int argc,char* argv[])
{
@autoreleasepool{
APPLECar* car = [[APPLECar alloc]init];
car.brand = @"BMW";
car.model = @"X5";
car.color = @"red";
[car drive];
[car drive:@"tom"];
}
}