2011-02-05 117 views
2

我在的.h文件下面的代碼:爲什麼NSString變量需要保留?

@interface Utils : NSObject { 
    NSString *dPath; 
}  
@property(nonatomic, retain) NSString *dPath; 

在我的.m文件

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
dPath = [[documentPaths objectAtIndex:0] stringByAppendingPathComponent:kDatabaseName]; 
[dPath retain]; 

爲什麼我要保留dPath如果它已被定義爲(非原子,保留)? 如果我不添加[dPath retain];我收到了一些奇怪的隨機錯誤,並在其他函數中使用此變量時應用程序崩潰。我想這是因爲一些autorelease somehere,但我沒有任何。

那麼,什麼是(非原子,保留)做呢?是否真的有必要[dPath retain];或者我只是用這個隱藏別的東西?

+0

如果您在Utils中設置了dPath,請確保您使用的是self.dPath,而不僅僅是dPath – anq 2011-02-05 06:36:54

回答

7

由於代碼不調用dPath屬性的setter方法,它只是設置實例變量dPath直接:

dPath = [[documentPaths objectAtIndex:0] stringByAppendingPathComponent:kDatabaseName]; 
[dPath retain]; 

所以它需要手動保留。

您將能夠(其實你需要)省略retain調用如果屬性setter中使用這樣的(注意self.):

self.dPath = [[documentPaths objectAtIndex:0] stringByAppendingPathComponent:kDatabaseName]; 

或類似這樣(注意setDPath:):

[self setDPath:[[documentPaths objectAtIndex:0] stringByAppendingPathComponent:kDatabaseName]]; 

的制定者保留了NSString給你,讓你不必自己做。


一個不錯的小練習,以避免混亂跟隨,是貼上下劃線您伊娃的名字,以表明它是伊娃:

NSString *dPath_; 

然後合成你的財產就是這樣,以它與你的不同名稱伊娃關聯:

// self.dPath is the property, dPath_ is the ivar 
@synthesize dPath = dPath_; 

然後修改dealloc方法,以及直接引用實例VAR任何其他代碼,使用該貼名稱,而不是:

- (void)dealloc { 
    [dPath_ release]; 

    [super dealloc]; 
} 
+0

我剛剛根據您的建議更改了代碼,並且它正在工作。直到現在沒有崩潰。我想我需要回到Objective-C的基本內容:(謝謝!! – KVron 2011-02-05 06:43:16

0

嘗試設置與

self.dPath 
0

得到它。如果你想調用屬性setter方法,這將調用保留,那麼你想寫:

self.dPath = ... 

干擾的東西到一個變量與:

dPath = ... 

完全忽略此實例變量的屬性。這就是爲什麼你最終需要手動進行保留。

相關問題