我正在閱讀memory management的蘋果文檔,遇到了一些我只是不明白的東西。基本上,我不明白爲什麼不需要通過「getter」方法保留一個實例變量。我寫了這個小程序來看看會發生什麼。我以爲會有一個崩潰,但我顯然錯過了一些東西。Objective C內存管理混亂
// main.m
// Test
//
#import <Foundation/Foundation.h>
#import "Test.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
//Initialize the test object
Test *t = [[Test alloc] init];
//Set the value to 5
[t setMyNum:[NSNumber numberWithInt:5]];
//Save a temp number that points to the original number
NSNumber *tempNum = [t myNum];
//release old number and retain new
[t setMyNum:[NSNumber numberWithInt:7]];
//Shouldn't this crash because tempNum is pointing to a deallocated NSNumber???
NSLog(@"the number is %@",tempNum);
[p drain];
return 0;
}
是不是tempNum指向一個釋放對象?
所有幫助表示讚賞。
編輯這是getter和setter方法
#import "Test.h"
@implementation Test
- (void)setMyNum:(NSNumber *)newNum {
[newNum retain];
[myNum release];
myNum = newNum;
}
-(NSNumber *)myNum {
return myNum;
}
@end
正如你看到的,我呼籲舊的對象上發佈的代碼。
編輯有人建議,我認爲是正確的,所以tempNum仍然在附近的原因是因爲它還沒有從池中autoreleased。但即使在NSLog消息之前移動[pool drain]之後,也沒有崩潰?奇怪的。
但在我的setMyNum中,我明確地調用retain和release。我呼籲釋放後,舊號碼會發生什麼? – esiegel 2009-05-25 18:51:52
版本不會釋放對象,它只是從該對象的「保留計數」中減去一個。只有當保留計數達到0時,對象纔會被釋放。在你的情況下,編號(代表5的NSNumber)在創建後有一個直接的保留計數,然後當它在Test對象中設置時增加到2,然後當另一個NSNumber(代表7)獲得時遞減到1在Test對象中設置。 – harms 2009-05-25 18:56:43