Objectice-C申明一个car接口如下:
#import <Foundation/Foundation.h>
@interface Car : NSObject
{
int year;
NSString *make;
NSString *model;
}
- (void) setMake:(NSString *) aMake andModel:(NSString *) aModel andYear: (int) aYear;
- (void) printCarInfo;
- (int) year;
@end
实现该接口:
#import "Car.h"
@implementation Car
- (id) init
{
self = [super init];
if (!self) return nil;
make = nil;
model = nil;
year = 1901;
return self;
}
- (void) setMake:(NSString *) aMake andModel:(NSString *) aModel andYear: (int) aYear
{
make = [NSString stringWithString:aMake];
model = [NSString stringWithString:aModel];
year = aYear;
}
- (void) printCarInfo
{
if (!make) return;
if (!model) return;
printf("Car Info\n");
printf("Make: %s\n", [make UTF8String]);
printf("Model: %s\n", [model UTF8String]);
printf("Year: %d\n", year);
}
- (int) year
{
return year;
}
@end
创建对象:
Car *myCar = [[Car alloc] init];
采用先分配内存然后调用的方式,此时sizeof(myCar)的大小为4,sizeof(*myCar)大小为16.
释放对象:
[myCar release];