gpt4 book ai didi

objective-c - 在 Setter 中保留计数和复制?

转载 作者:行者123 更新时间:2023-12-03 16:52:00 24 4
gpt4 key购买 nike

这是上一个问题的后续问题,希望更清楚一些。我只是好奇下面的代码是如何工作的,特别是变量 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];
}

加里

最佳答案

is the variable myString getting released.

[myString release];

所有迹象都表明是。

It does not look like it is from the output?

NSLog(@"RetainCount_2: %d",[myString retainCount]);
[myString release];

您的 NSLog 语句的输出不会反射(reflect) release 消息,因为 release 消息尚未发生。

另外,不用担心保留计数。它们可能非常具有误导性。只要您遵循 Cocoa 的规则并且不创建任何所有权循环(A 拥有 B 拥有 C 拥有 A),您就很少会遇到问题。

关于objective-c - 在 Setter 中保留计数和复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1502637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com