Dealloc方法的使用

今天我们来学习一下Dealloc方法的使用。Dealloc方法的作用是,当对象的引用计数为0时,系统会自动调用dealloc方法来回收内存。它的一般写法有两种:

1. 调用父类的dealloc方法:

```objective-c

-(void)dealloc{

[super dealloc];

}

```

2. 调用父类的dealloc方法并释放子类拥有的对象实例:

```objective-c

-(void)dealloc{

NSLog(@"laptop dead");

[_cpu release];

[super dealloc];

}

```

接下来我们来了解一下为什么需要调用父类的dealloc方法以及调用的顺序。

(一)为什么需要调用父类的dealloc方法?

子类的对象实例有时是继承自父类的。因此,我们需要调用父类的dealloc方法来释放父类拥有的这些对象。

(二)调用的顺序

一般来说,调用的顺序是先释放子类的对象实例,然后再释放父类所拥有的实例。这一点与调用初始化方法正好相反。下面我们使用一个例子来演示一下:

1. 父类Vehicle.h

```objective-c

#import

@interface Vehicle : NSObject {

@private

NSString *_name;

}

-(id)initWithName:(NSString *)name;

@end

```

2. 父类Vehicle.m

```objective-c

#import "Vehicle.h"

@implementation Vehicle

-(id)initWithName:(NSString *)name{

self=[super init];

if(self){

_name=[name copy];

}

return self;

}

-(void)dealloc{

NSLog(@"vehicle dead");

[_name release];

[super dealloc];

}

@end

```

3. 子类Car.h

```objective-c

#import

#import "Vehicle.h"

@class Engine;

@interface Car : Vehicle {

Engine *_engine;

}

-(void)setEngine:(Engine *)engine;

@end

```

:子类Car.m

```objective-c

#import "Car.h"

@implementation Car {

Engine *_engine;

}

- (void)setEngine:(Engine *)engine {

if (_engine != engine) {

[_engine release];

_engine = [engine retain];

}

}

- (Engine *)engine {

return _engine;

}

- (void)dealloc {

NSLog(@"Car dead");

[_engine release];

[super dealloc];

}

@end

```

5:测试main.m代码

```objective-c

#import

#import "Engine.h"

#import "Car.h"

int main(int argc, const char *argv[]) {

@autoreleasepool {

NSString *name = [[NSString alloc] initWithFormat:@"audi"];

Car *car = [[Car alloc] initWithName:name];

[name release];

Engine *v6 = [[Engine alloc] init];

[car setEngine:v6];

[v6 release];

//do something

[car release];

}

return 0;

}

```