這是上一個問題的後續問題,希望更清楚一點。我只是好奇下面提供的代碼是如何工作的,特別是變量myString被髮布。它看起來不像是從輸出?保留計數並複製二傳手?
CODE
// IMPLEMENT
@implementation CelestialBody
- (void)setName:(NSString *)newName{
if(name != newName) {
[name release];
name = [newName copy];
}
}
- (void)dealloc{
[name release];
name = nil;
[super dealloc];
}
@end
。
// ------------------------------------------------------------------- **
// MAIN: 30th September 2009
// ------------------------------------------------------------------- **
#import <Foundation/Foundation.h>
#import "CelestialBody.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
CelestialBody *newPlanet = [[CelestialBody alloc] init];
NSString *myString = [[NSString alloc]initWithFormat:@"go home"];
NSLog(@"RetainCount_1: %d",[myString retainCount]);
[newPlanet setName: myString];
NSLog(@"RetainCount_2: Incremented by copy in setName");
// Clean up
NSLog(@"RetainCount_2: %d -Before Release",[myString retainCount]);
[newPlanet release];
[myString release];
[pool drain];
NSLog(@"RetainCount_1: %d -After Release",[myString retainCount]);
return 0;
}
// ------------------------------------------------------------------- **
輸出
Running…
2009-10-01 09:28:50.395 RetainCount_1: 1
2009-10-01 09:28:50.399 RetainCount_2: Incremented by copy in setName
2009-10-01 09:28:50.399 RetainCount_2: 2 -Before Release
2009-10-01 09:28:50.400 RetainCount_1: 1 -After Release
Debugger stopped.
我目前重新讀Memeory管理指南試試,看看我已經錯過了。
千恩萬謝
編輯
只是增加了一個釋放的dealloc的,看起來這是我失蹤了。
- (void)dealloc{
[name release];
name = nil;
[super dealloc];
}
加里
不用擔心-retainCount。別叫它。不要打印它。不要考慮它。這沒有用。保持計數應被視爲增量;你增加和減少,但潛在價值不是你關心的。 – bbum 2009-10-01 15:52:43