这是上一个问题的后续问题,希望可以更清楚一些。我很好奇下面介绍的代码是如何工作的,特别是变量myString被释放了。它看起来不是从输出中来的吗?
码
// 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.
我目前正在重新阅读《内存管理指南》,以尝试查看错过的内容。
非常感谢
编辑
刚刚将一个发行版添加到了dealloc中,这似乎是我所缺少的。
- (void)dealloc{
[name release];
name = nil;
[super dealloc];
}
加里
最佳答案
是变量myString被释放。
[myString release];
所有迹象都表明是。
它看起来不是从输出中来的吗?
NSLog(@"RetainCount_2: %d",[myString retainCount]);
[myString release];
您的NSLog语句的输出未反映
release
消息,因为release
消息尚未发生。另外,不必担心保留计数。他们可能会产生误导。只要您遵循Cocoa的规则并且不创建任何所有权周期(A拥有B拥有C拥有A拥有),您就很少有问题。
关于objective-c - 保留计数并复制在二传手中吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1502637/