2010-11-05 31 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

相關問題