在非 ARC 的開發環境中,dealloc 是一個類釋放前清理內存的最後機會。哪些變量和屬性該在這裡釋放?NSTimer、通知、delegate 這些特殊對象又該怎麼處理?
需要特別小心的是:不釋放會導致內存洩露,而過度釋放同樣會引發洩露甚至崩潰。下面按類別逐個展開。
變量聲明:
@interface EnterHondaViewController : UIViewController {
UIImageView *imageLogo;
UIButton *btn_Corporate;
UIButton *btn_Brand;
CorporateView *corporateview;
BrandView *brandview;
}
@end
變量初始化(注意局部變量與成員變量的區別):
@implementation EnterHondaViewController
-(id)initWithFrame:(CGRect)frame
{
self = [super init];
if (self) {
self.view.frame = frame;
[self.view setBackgroundColor:[UIColor whiteColor]];
// 局部變量:addSubview 之後立刻 release
UIImageView *background = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
[self.view addSubview:background];
[background release];
[background setImage:[UIImage imageNamed:@"AllAuto_Image_BG"]];
UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(50, 18, 55, 40)];
[backBtn setImage:[UIImage imageNamed:@"home_button"] forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(onBack:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:backBtn];
[backBtn release];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 25, 400, 35)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = NSTextAlignmentLeft;
titleLabel.font = [UIFont fontWithName:@"Arial" size:30];
titleLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
[self.view addSubview:titleLabel];
[titleLabel release];
[titleLabel setText:@"走進廣本"];
// 成員變量:addSubview 後也要 release,因為 ivar 已經持有一份引用
imageLogo = [[UIImageView alloc] initWithFrame:CGRectMake(0, 6, 12, 13)];
[logoview addSubview:imageLogo];
[imageLogo release];
imageLogo.image = [UIImage imageNamed:@"AllAuto_Corporation_Button_Select"];
btn_Corporate = [[UIButton alloc] initWithFrame:CGRectMake(13, 0, 100, 25)];
[logoview addSubview:btn_Corporate];
btn_Corporate.tag = 1;
[btn_Corporate release];
[btn_Corporate addTarget:self action:@selector(onOptionClick:) forControlEvents:UIControlEventTouchUpInside];
[btn_Corporate setTitle:@"企業文化" forState:UIControlStateNormal];
// 這兩個成員變量沒有 addSubview,所有權留在 self 手裡
corporateview = [[CorporateView alloc] initWithFrame:CGRectMake(0, 110, frame.size.width, frame.size.height - 120)];
brandview = [[BrandView alloc] initWithFrame:CGRectMake(0, 110, frame.size.width, frame.size.height - 110)];
[btn_Corporate sendActionsForControlEvents:UIControlEventTouchUpInside];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onGoBrandPage:)
name:Notification_Navigate_To_Brand
object:nil];
}
return self;
}
變量釋放:
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[brandview release];
[corporateview release];
[super dealloc];
}
這裡有一個關鍵判斷標準:誰持有,誰釋放。alloc 之後立刻 addSubview 並 release 的(如 background、backBtn),所有權已經交給父視圖,self 不再需要負責;而 corporateview 和 brandview 沒有加入視圖層次,引用計數仍舊由 self 獨佔,就必須在 dealloc 中釋放。同一個 ivar 在不同地方遵循不同規則,取決於它是否被別人 retain 過。
屬性聲明:
@interface GGDetailCell : UIGridViewCell @end @property (nonatomic, retain) UILabel *labelTitle;
屬性初始化(用 autorelease 讓 setter 完成 retain,隨後由調用週期的 autorelease pool 平衡):
- (id)init
{
if (self = [super init]) {
self.frame = CGRectMake(0, 0, 66, 30.5);
{ // labelTitle
self.labelTitle = [[[UILabel alloc] initWithFrame:CGRectMake(0, 7, 66, 16)] autorelease];
[self.labelTitle setBackgroundColor:[UIColor clearColor]];
[self.labelTitle setTextColor:TEXT_COLOR_PART_NORMAL];
[self.labelTitle setFont:[UIFont systemFontOfSize:12]];
[self.labelTitle setNumberOfLines:0];
[self.labelTitle setTextAlignment:UITextAlignmentCenter];
[self addSubview:self.labelTitle];
}
}
return self;
}
屬性釋放——直接置 nil 即可,setter 會負責 release 舊值:
- (void)dealloc
{
self.labelTitle = nil;
[super dealloc];
}
寫成 self.xxx = nil 比直接 [xxx release] 更安全:如果 xxx 此時已經是 nil,向 nil 發消息無害;而重複 release 一個已釋放對象則會崩潰。
定時器聲明:
@interface BRLandscapeView
NSTimer *timer;
}
@end
定時器初始化:
-(void)myInit
{
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
}
定時器釋放:如果 timer 是在某個 view 中聲明並初始化的,必須在 controller 釋放該 view 之前先 invalidate,否則由於循環引用永遠釋放不掉。
@implementation BookReadController
-(void)dealloc
{
if (landscape) {
[landscape->timer invalidate];
}
SafeRelease(landscape);
[super dealloc];
}
@end
循環引用的成因是:timer 被 RunLoop 持有,同時 timer retain 了 target(這裡是 landscape),而 landscape 又持有 timer。三者成環,任何一環不打破都不會釋放。所以 invalidate 的時機必須早於 view 的釋放。
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
不解除註冊的後果是:通知到來時系統會向已釋放的對象發送 selector,直接崩潰。
delegate 屬性聲明時一般是 assign(避免循環引用),賦值對象通常就是 self。因此在相關 view 釋放之前,要先把 delegate 斷開:
情況一:
if (_loadingContentView) {
_loadingContentView.delegate = nil;
[_loadingContentView removeFromSuperview];
}
情況二:
self.partGridView.uiGridViewDelegate = nil; self.partGridView = nil;
如果一個函數需要返回在函數內部聲明並初始化的對象,卻又不能立即釋放,最合適的處理方式是 autorelease:
-(NSArray*)getTemplatesByPath:(NSString *)path
{
NSError *error = nil;
NSArray *files = [fileManager contentsOfDirectoryAtPath:path error:&error];
if (error != nil) {
return nil;
}
NSMutableArray *resultArray = [NSMutableArray new];
for (NSInteger index = 0; index < [files count]; index++) {
NSString *fileName = [files objectAtIndex:index];
NSString *extType = [fileName pathExtension];
if (NO == [extType isEqualToString:@"tpl"]) {
continue;
}
[resultArray addObject:fileName];
}
return [resultArray autorelease];
}
返回 autorelease 對象,意味著把釋放責任交給當前的 autorelease pool,調用方在 pool 排空之前都可以安全使用返回值,遵循的是 Cocoa 經典的三段式內存管理約定。
UIImageView *lineView = [[UIImageView alloc] initWithFrame:CGRectMake((frame.size.width - 658) / 2, 70, 658, 8)]; lineView.image = [UIImage imageNamed:@"AllAuto_Config_TimeLine_BG"]; [self.view addSubview:lineView]; [lineView release];
addSubview 之後立刻 release,是 MRC 時代最標準的寫法:alloc 佔一份,父視圖 retain 佔一份,release 抵消自己那份,引用計數歸父視圖所有。
在 iOS 的第一版中,我們為 outlet 同時聲明了屬性和底層實例變量。那時屬性是 Objective-C 的新機制,並且強制要求你聲明與之對應的實例變量:
@interface MyViewController : UIViewController
{
UIButton *myButton;
}
@property (nonatomic, retain) UIButton *myButton;
@end
後來蘋果把默認編譯器從 GCC 換成了 LLVM,從此不再需要為屬性聲明實例變量。如果 LLVM 發現一個沒有匹配 ivar 的屬性,它會自動創建一個以下劃線開頭的實例變量:
@interface MyViewController : UIViewController @property (nonatomic, retain) UIButton *myButton; @end
在 .m 中,編譯器會自動生成 _myButton,因此你可以直接使用 _myButton,也可以通過 self.myButton,兩者等價——但要注意 self.myButton 實際上是調用屬性的 getter / setter,而 _myButton 是直接訪問 ivar。
這與 C++ 中「點」的用法有本質區別。在 OC 中:
// .h
@interface MyViewController : UIViewController
{
NSString *name;
}
@end
// .m 中,self.name 是錯誤的,Xcode 會提示改用 ->
// 改成 self->name 才可以
因為 OC 的點表達式表示調用方法,而上面並沒有 name 這個方法。官方語法說明寫得很清楚:
點表達式 (.) 看起來與 C 語言中的結構體訪問以及 Java 語言中的對象訪問有點類似,其實這是 OC 的設計人員有意為之。如果點表達式出現在等號 = 左邊,該屬性名稱的 setter 方法將被調用;如果出現在右邊,該屬性名稱的 getter 方法將被調用。
所以在 OC 裡,點表達式其實就是調用 setter / getter 的快捷方式:
dealie.blah = greeble; // 完全等價於 [dealie setBlah:greeble];
@synthesize 的作用演變。 舊寫法是同時聲明屬性與 ivar;iOS 5 之後蘋果建議只寫屬性:
@interface MyViewController : UIViewController @property (nonatomic, retain) UIButton *myButton; @end
此時編譯器會自動生成以下劃線開頭的 ivar _myButton,也無需再寫 @synthesize myButton;,setter 與 getter 都會自動生成。
而 @synthesize 有兩個作用:一是讓編譯器生成 setter / getter;二是指定與屬性對應的 ivar。例如 @synthesize myButton = xxx;,那麼 self.myButton 操作的就是 xxx 而非 _myButton。
實務中的細微差別在於:
· 寫了 @synthesize myButton; → 生成的 ivar 名是 myButton,此時 _myButton 並不存在。
· 沒寫 @synthesize → 生成的 ivar 名是 _myButton。
類別中的屬性是特例。 類別(category)中只能添加方法,不能添加實例變量,因此在類別中添加屬性時不會自動生成 ivar,實際添加的只是 getter 與 setter 方法。例如:
@interface UIViewController (UINavigationControllerItem) @property(nonatomic, readonly, retain) UINavigationItem *navigationItem; @property(nonatomic) BOOL hidesBottomBarWhenPushed; @property(nonatomic, readonly, retain) UINavigationController *navigationController; @end
這裡添加的屬性並不會自動生成實例變量。需要注意:匿名類別(匿名擴展)是可以添加實例變量的,非匿名類別則不行。
iOS 5 引入的 ARC 極大簡化了內存管理,規則非常簡單:
只要還有一個變量指向對象,對象就會保持在內存中。當指針指向新值,或者指針不再存在時,相關聯的對象就會被自動釋放。
這條規則對實例變量、synthesize 屬性、局部變量一律適用。
以前沒有 ARC 時,必須寫 dealloc 手動釋放:
- (void)dealloc
{
[_myTableView release];
[super dealloc];
}
使用 ARC 之後,不再需要 dealloc 來釋放內存,也不必再操心 release 的配對問題,系統會全權接管。
不過要注意,ARC 並非萬能:Core Foundation 對象(CGImageRef、CGColorRef 等)、malloc 分配的內存、以及手動創建的 C 結構體,仍然需要你自己管理釋放。另外,即便在 ARC 下,通知的 removeObserver 與 timer 的 invalidate 依然要寫——ARC 只管引用計數,管不了「向已釋放對象發消息」這類邏輯問題。