您好,登錄后才能下訂單哦!
今天來學習一下Dealloc方法的使用。
它的作用是,當對象的引用計數為0,系統會自動調用dealloc方法,回收內存。它的一般寫法:
1:-(void)dealloc{
[super dealloc]; }
2:-(void)dealloc{NSLog(@"laptop dead"); [_cpu release]; [super dealloc]; }(一):為什么需要調用父類的dealloc方法?
子類的某些對象實例是繼承自父類的。因此,我們需要調用父類的dealloc方法,來釋放父類
擁有的這些對象。
(二):調用的順序
一般說調用的順序是,當子類的對象釋放完時,然后再釋放父類的所擁有的實例。這一點與調用初始化方法,
正好相反
下面使用一個例子來演示一下:
1:父類Vehicle.h
#import <Foundation/Foundation.h> @interface Vehicle : NSObject { @private NSString *_name; } -(id)initWithName:(NSString *)name; @end2:父類Vehicle.m
#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]; } @end3:子類Car.h#import <Foundation/Foundation.h> #import "Vehicle.h" @class Engine; @interface Car : Vehicle { Engine *_engine; } -(void)setEngine:(Engine *)engine; @end4:子類Car.m#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 <Foundation/Foundation.h> #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; }運行截圖
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。