Main.m
#import "Car.h"
#import "Engine.h"
/*
定义汽车Car, 引擎(Engine), 汽车持有引擎的对象所有权。
*/
int main(int argc, const char * argv[])
{
Car *car = [[Car alloc] init];
Engine *engine = [[Engine alloc] init];
car.engine = engine;
[car release];
[engine release];
// [car run];
//此时不能调用,car不存在了,调用了野指针
//空指针:
// Car *car1 = nil; //car1:空指针
return 0;
}
Car.h
@class Engine;
@interface Car : NSObject {
Engine *_engine;
NSString *_name;
float _speed;
}
//启动汽车
- (void)run;
- (void)setEngine:(Engine *)engine;
- (void)setName:(NSString *)name;
- (void)setSpeed:(float)speed;
//自定义初始化
- (id)initWithEngine:(Engine *)engine;
Car.m
#import "Engine.h"
@implementation Car
- (void)dealloc
{
NSLog(@"car dealloc");
[_engine release];
[_name release];
[super dealloc];
}
//启动汽车
- (void)run {
NSLog(@"%@",_engine);
}
- (void)setEngine:(Engine *)engine {
if (_engine != engine) {
[_engine release];
_engine = [engine retain];
}
}
- (void)setName:(NSString *)name {
if (_name != name) {
[_name release];
_name = [name copy];
}
}
//基本数据类型不需要内存管理
- (void)setSpeed:(float)speed {
_speed = speed;
}
//自定义初始化
- (id)initWithEngine:(Engine *)engine {
self = [super init];
if (self ) {
_engine = [engine retain];
}
return self;
}
Engine.h
@interface Engine : NSObject
Engine.m
@implementation Engine
- (void)dealloc
{
NSLog(@"engine dealloc");
[super dealloc];
}