【问题标题】:Why is my retain count for the variable inputString eleven here?为什么我的变量 inputString 的保留计数在此处为 11?
【发布时间】:2010-08-08 22:08:13
【问题描述】:

我正在尝试了解 Objective-C 中的内存管理。到目前为止,我一直在使用垃圾收集器,但在继续之前,我想更好地了解手动管理内存。我知道我在这段代码中没有实现 dealloc 方法。

我的问题是为什么我的 inputString 变量在这里的保留计数为 11?

#import "AppController.h"


@implementation AppController

-(id) init
{
 [super init];
 NSLog(@"init");
 speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
 NSLog(@"speechSynth retain count is %d",[speechSynth retainCount]);
 return self;
}


-(IBAction) count:(id) sender
{
 NSString *outputString;
 int numberOfCharacters;

 inputString = [textField stringValue];
 numberOfCharacters = [inputString length];
 outputString = [NSString stringWithFormat:@"\"%@\" has %d characters",inputString,numberOfCharacters];

 [label setStringValue:outputString];
 [speechSynth startSpeakingString:outputString];
 NSLog(@"outputString retain count is : %i",[outputString retainCount]);
 NSLog(@"inputString retain count is: %d",[inputString retainCount]);
 NSLog(@"speechSynth retain count is: %d",[speechSynth retainCount]);
 [outputString release];
}
@end

【问题讨论】:

    标签: objective-c memory-management


    【解决方案1】:

    Apple 的回答是“没关系”。正确跟踪您的引用,并让运行时整理其余部分。

    在内部,运行时可能会给你一个指向单例空字符串的指针(因为 NSStrings 是不可变的)。或者它可能正在做其他事情。但是,从您的角度来看,刚刚分配的变量的引用计数背后的原因被认为是运行时内部,您不应该依赖它来做任何事情。

    使用 Instruments 和僵尸对象来确定您是在泄漏还是过度释放,并假装 retainCount 消息不存在。

    【讨论】:

    • 顺便说一句: outputString 不应该被释放,因为你还没有对其进行保留。看起来 inputString、numberOfCharacters 和 outputString 都应该是局部变量,因为您既没有通过调用保留显式保留它们,也没有通过使用 setter 方法([self setInputString:...] 或self.inputString = ...)。
    • 说真的,“假装retainCount 不存在”是您在该主题上可以获得的最佳建议。 autorelease 会使保留计数无用查看,即使它还没有。
    【解决方案2】:

    你认为 inputString 应该有多少保留计数?请记住,您是从 Cocoa 框架中获得它的,谁知道其中有多少不同的对象引用了它——可能有 11 个。

    查看Memory Management Rules。他们根本没有提到保留计数,这是有充分理由的:它们作为调试工具几乎毫无用处。

    【讨论】:

      【解决方案3】:

      来自 Apple 文档:

      重要提示:通常应该有 没有理由明确询问对象 它的保留计数是多少(参见 保留计数)。结果往往 误导,因为您可能不知道 框架对象保留了什么 您感兴趣的对象。 在调试内存管理问题时, 你应该只关心 确保您的代码符合 所有权规则。

      Apple Documentation 谢谢大家的帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-13
        • 1970-01-01
        • 1970-01-01
        • 2011-06-10
        • 1970-01-01
        • 2011-02-17
        • 1970-01-01
        • 2011-05-19
        相关资源
        最近更新 更多