2012-02-29 57 views
0

我已經使用了下面的代碼。殭屍報告:發送到釋放實例的消息

MainView.h:

NSString *sCopySource; 
NSString *sFileSource; 

// retain and copy used both for test proposes 
@property (nonatomic, retain) NSString *sCopySource; 
@property (nonatomic, copy) NSString *sFileSource; 

MainView.m:

// Inside the first method: 
sCopySource = [NSString stringWithFormat:@"%@%@", path1, filename]; 
sFileSource = [NSString stringWithFormat:@"%@%@", path2, filename]; 

// Inside the second method: 
[[NSFileManager defaultManager] copyItemAtPath:sCopySource toPath:sFileSource error:&err]; 

而採取錯誤的啓用殭屍的對象sCopySourcesFileSource代碼的最後一行:

message sent to deallocated instance 

爲什麼?標記爲retaincopy的屬性。如何解決這個問題?

非常感謝您的幫助!

P.S.請不要回答使用ratainrelease方法。他們非常不方便。

回答

2

您已經定義了屬性,但是您正在直接寫入實例變量。

如果你想使用保留/釋放邏輯屬性,你需要使用:

self.sCopySource = [NSString stringWithFormat:@"%@%@", path1, filename]; 
    self.sFileSource = [NSString stringWithFormat:@"%@%@", path2, filename]; 

這樣一來,所使用做拷貝,並保留方法。

+0

gaige,非常感謝!什麼是最好的 - 保留還是複製? – Dmitry 2012-02-29 19:36:29

+0

取決於你在做什麼。複製保證你保留的版本不會變異。另一方面,保留對原始對象的引用,如果原始類是可變的,則原始對象可能會變異。通常,保留是足夠的和更高效的,但當您使用可能在代碼中的其他位置發生變異的值時,複製可能是必需的。 – gaige 2012-02-29 19:38:31

+0

再次感謝! – Dmitry 2012-02-29 19:50:23

相關問題