【问题标题】:Incorrect decrement of the reference count of an object that is not owned at this point by the caller调用者此时不拥有的对象的引用计数不正确递减
【发布时间】:2011-05-05 21:22:39
【问题描述】:

我有一个非常简单的 Person 类,它有一个名为 name 的 ivar(一个 NSString)。当我尝试在 dealloc 中释放这个 ivar 时,静态分析器给了我一个奇怪的错误:

引用减量不正确 不拥有的对象的计数 此时由调用者

我做错了什么?

顺便说一句,这是我的代码:

@interface Person : NSObject {

}

@property (copy) NSString *name;
@property float expectedRaise;

@end


@implementation Person

@synthesize name, expectedRaise;

-(id) init {
    if ([super init]) {
        [self setName:@"Joe Doe"];
        [self setExpectedRaise:5.0];
        return self;
    }else {
        return nil;
    }

}

-(void) dealloc{
    [[self name] release]; // here is where I get the error
    [super dealloc];
}

@end

【问题讨论】:

    标签: objective-c cocoa memory-management


    【解决方案1】:

    您正在释放从属性 getter 方法返回的对象,这在许多情况下表明可能存在错误。这就是静态分析的原因。

    改为:

    self.name = nil;
    

    或:

    [name release];
    name = nil;
    

    【讨论】:

    • 最好是后者。 Apple 建议不要在 init 和 dealloc 方法中使用 getter 或 setter。
    • 也可以放在一行,用逗号分隔[name release], name = nil
    • 如果子类中有观察者或覆盖触发行为,它将从dealloc 触发,这几乎不是你想要的(因为对象的状态会不一致) .
    • @bbum 但是为什么release= nil 呢?第一个还不够吗?
    • 在 ARC 下不再需要防御的旧习惯。如果没有 ARC,简单地释放 name 将使变量仍然引用 [可能现在以前的] 对象。如果还有其他消息要发给它,BOOM。如果你想主动防御——找到你在name发布后发消息的情况——使用name = (id)0x1;;这将保证崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多