2010-10-28 56 views
0

我有以下簡單的代碼:爲什麼retainCount在釋放被調用後返回值?

NSMutableArray *array = [[NSMutableArray alloc] init]; 

    NSObject *o = [[NSObject alloc] init]; 
    NSObject *o1 = [[NSObject alloc] init]; 
    NSObject *o2 = [[NSObject alloc] init]; 

    [array addObject:o]; 
    [array addObject:o1]; 
    [array addObject:o2]; 
    NSLog(@"-------"); 
    NSLog(@"%d, %d, %d, %d\n", [o retainCount], [o1 retainCount], [o2 
                    retainCount], [array retainCount]); 
    [array release]; 
    NSLog(@"%d, %d, %d, %d\n", [o retainCount], [o1 retainCount], [o2 
                    retainCount], [array retainCount]); 
    [o release]; 
    [o1 release]; 
    [o2 release]; 
    NSLog(@"-------"); 
    NSLog(@"%d, %d, %d, %d\n", [o retainCount], [o1 retainCount], [o2 
                    retainCount], [array retainCount]); 

作爲輸出我得到:

[Session started at 2010-10-27 18:00:59 +0200.] 
2010-10-27 18:01:02.186 Questions[22463:207] ------- 
2010-10-27 18:01:02.187 Questions[22463:207] 2, 2, 2, 1 
2010-10-27 18:01:02.188 Questions[22463:207] 1, 1, 1, 1 
2010-10-27 18:01:02.188 Questions[22463:207] ------- 

,並且程序用EXC_BAD_ACCESS壓碎。

我的問題是以下幾點: 我明白,打完電話後[陣列發行]數組對象不存在了,對不對?對於其他對象的調用釋放也是如此,對嗎?如果是這樣,爲什麼我調用[array retainCount]後沒有得到EXC_BAD_ACCESS?爲什麼它返回任何值?以及爲什麼在其他對象上調用retainCount會導致EXC_BAD_ACCESS?

感謝您的幫助!

回答

3

好吧,正如你正確地猜到你不能發送消息到已經發布的對象。如果你這樣做的行爲是未指定的,所以EXC_BAD_ACCESS可能會被提出,但它不需要。

如果你想從你已經發布的objets中獲得retainCount,你應該檢查出NSZombieEnabledhttp://www.cocoadev.com/index.pl?NSZombieEnabled),這會導致對象被釋放但不會被釋放。

2

因爲你發佈array,然後嘗試再次訪問它。

[array release]; // array is no longer in memory, therefore you can no longer use it. 
[array retainCount]; // crash! 

即使你打電話release對象上,有時該對象可以保留在內存中稍長。我建議你在釋放它之後設置任何你可以重用的變量到nil

[array release]; 
array = nil; 
[array retainCount]; // no more crash 
相關問題