不穩定的autorelease

結論:如果有一個實例A是用工廠方法創建或被聲明爲autorelease的,則當代碼執行到跳出這一實例化A的代碼塊(例如一個function)且實例A並沒有被保留(retain)下來時,實例A的指針所指向的內容將被釋放

示例:

#import "ViewController.h"
#import "TestViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    // 1、被聲明爲autorelease的視圖控制器
    testVC = [[[TestViewController alloc] initWithNibName:nil bundle:nil] autorelease];
    [self.view insertSubview:testVC.view atIndex:0];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 2、向已經被釋放的視圖控制器發送消息,引起了crash
- (IBAction)buttonClicked:(id)sender
{
    [testVC doSomething];
}
@end

     所以,如果過分依賴系統提供的自動釋放的機制,將會導致一些莫名其妙的crash。autorelease似乎並不是那麼靠得住,所以爲了提供程序的健壯性,在實例化類的時候最好採用alloc:init這樣穩健的創建方式。不過要注意alloc之後要release。
    今天先到這裏,希望它對您有所幫助!!!


發佈了28 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章