2010-11-05 33 views
4

我有一个非常简单的Person类,它有一个名为(一个NSString)的ivar。当我尝试在dealloc中释放此ivar时,静态分析器给了我一个奇怪的错误:调用者此时没有拥有的对象的引用计数的错误递减

Incorrect decrement of the reference count of an object that is not owned at this point by the caller

我在做什么错?

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

@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 

回答

18

你释放的对象从属性的getter方法,在许多情况下将是一个可能的错误的指示返回。这就是为什么静态分析正在挑选它。

相反,使用:

self.name = nil; 

或:

[name release]; 
name = nil; 
+4

优选后者。 Apple建议不要在init和dealloc方法中使用getter或setter。 – Chuck 2010-11-06 00:16:59

+1

是的。后者ftw。 – bbum 2010-11-06 00:43:30

+1

你也可以把它放在一行,用逗号分隔'[name release],name = nil' – Abizern 2010-11-06 05:40:45

相关问题