2010-09-09 144 views
1

你好Stackoverflow家庭成員!iPhone內存管理

我有關於iPhone內存管理的問題。

我所做的理解是以下方法

-(void) dealloc 
{ 
    // something else to release whatever 
    // such as Object Created using keyword 'alloc' 
    // but also Object destroy here its retain value reaches iff 0 
    // if I do put here NSLog(@"%d", [obj retainCount]); and when it reaches 
    // not equal to 0 means failure with memory leak. 
    [super dealloc]; 
} 

所以我是明白了吧?或者即使保留計數在這裏達到0以上,它仍然很亮?

我之所以問這個問題,因爲,

NSLog(@"%d", obj.retainCount); 

檢查,以檢查保留對象的數量和接收到的值3。於是,我就在這裏釋放的3倍,使這裏retainCount等於0,但編譯器給我提供了嚴重錯誤。

請問,我是新來的內存解除分配和保留,釋放。我用

對象是 '的UIImageView' 對象,並創建另一個實例是,

UIImageView *imageView = //da da~ with UIImage 
UIImageView *instance; 
// at this point retain count was '1' 
instance = imageView; 
//[imageView retain]; 
// at this point retain count was '2' 
[self.view addSubView: imageView]; 
// at this point retain count was '3' 
[imageView release];// crashes 
// at this point retain count was '2' 

,但如果我這樣做

// but if I add retain on the 'instance = imageView' 
// such as 
instance = imageView; // then 
[imageView retain]; 
// works but still count is 2... 

謝謝。

回答

1

覆蓋dealloc的正常過程是釋放之前由此實例保留(或分配)的任何對象。

所以,如果某處對象否則你有一個名爲頁頭或保留方法您的dealloc會是什麼樣子:

-(void)someOtherMethod 
{ 
    UIImageView *imageView = //da da~ with UIImage 
    UIImageView *instance; 
    instance = imageView; 
    [instance retain]; 
} 

-(void) dealloc 
{ 
    //release any retained objects here 
    [instance release]   
    [super dealloc]; 
} 

注意,如果推出後,計數未下降到零也無所謂你的特定版本,這只是意味着其他一些代碼也保留了對象內存(而另一部分代碼將負責釋放它)。

希望這會有所幫助。

5

retainCount不是一個可靠的調試工具:

  • 其他對象可能仍然持有引用obj
  • 還有,你不能破壞物體(如string constants
  • 對象被釋放,如果發佈時保留數爲1

你應該照顧的是:

0

這是不正確的release/autorelease

  • 適量,你應該很少使用retainCount。它不一定是0,因爲其他對象可能會引用正在釋放的對象。在dealloc中重要的是釋放你擁有所有權的對象。哪些是使用alloc或new創建的對象。