今天來學習一下Dealloc方法的使用。
它的作用是,當對象的引用計數為0,系統會自動調用dealloc方法,回收內存。它的一般寫法:
1:-(void)dealloc{
[super dealloc]; }
2:-(void)dealloc{
NSLog(@"laptop dead"); [_cpu release]; [super dealloc]; }(一):為什麼需要調用父類的dealloc方法?
子類的某些對象實例是繼承自父類的。因此,我們需要調用父類的dealloc方法,來釋放父類
擁有的這些對象。
(二):調用的順序
一般說調用的順序是,當子類的對象釋放完時,然後再釋放父類的所擁有的實例。這一點與調用初始化方法,
正好相反
下面使用一個例子來演示一下:
1:父類Vehicle.h
#import2:父類Vehicle.m@interface Vehicle : NSObject { @private NSString *_name; } -(id)initWithName:(NSString *)name; @end
#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
#import4:子類Car.m#import "Vehicle.h" @class Engine; @interface Car : Vehicle { Engine *_engine; } -(void)setEngine:(Engine *)engine; @end
#import "Car.h"
@implementation Car
-(void)setEngine:(Engine *)engine{ if(_engine!=engine){ [_engine release]; _engine=[engine retain]; } } -(Engine *)engint{ return _engine; } -(void)dealloc{ NSLog(@"Car dead"); [_engine release]; [super dealloc]; } @end5:測試main.m代碼
#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; }