2011-04-05 120 views
1
.h 

@ interface MyClass : NSObject { 
    UILabel *mTextLabel; 
} 

@property (nonatomic, retain) UILabel *mTextLabel; 

,並在MyClass.m聲明@synthesize mTextLabel;我不知道爲什麼我得到EXC_BAD_ACCESS(使用@property保留)

並釋放這樣的對象。

[self setMTextLabel:nil]; 
[mTextLabel release]; 
NSLog (@"%d",[mTextLabel retainCount]); 

這個結果是0.我沒有發現任何錯誤或中斷。

但是。當我像這樣釋放mTextLabel時。我剛剛得到了EXC_BAD_ACCESS

[mTextLabel release]; 
[self setMTextLabel:nil]; 

我不明白爲什麼會發生。 Plz幫助我。

+0

如果使用'self.mTextLabel = nil',會發生同樣的情況嗎? – 2011-04-05 20:39:53

+0

hm ...現在我使用'mTextLabel = nil'謝謝。 – Beomseok 2011-04-05 20:49:59

+0

保留計數不能爲零。不應該調用retainCount。這是無用的。 – bbum 2011-04-06 15:01:32

回答

6

當您具有retain屬性的綜合屬性時,合成setter在設置新值之前調用舊伊娃上的釋放。

下面是在第一個例子中發生的擴展視圖:

[mTextLabel release]; 
mTextLabel = nil; 
[mTextLabel release]; 

由於調用方法在零指針什麼也不做,就沒有問題。

在第二個例子,這裏是正在發生的事情:

[mTextLabel release]; 
[mTextLabel release]; 
mTextLabel = nil; 

看這個問題?

編輯:同樣值得注意的是,檢查一個對象的保留數很少有用,因爲任何數量的Cocoa類都可以保留它以用於他們自己的目的。您只需確保每次在對象上調用retain,alloc,copynew時,代碼中就會有一個匹配的releaseautorelease

+0

很好放。 :-) – 2011-04-05 20:48:41

+0

現在我沒有任何中斷或錯誤。謝謝。 – Beomseok 2011-04-05 20:55:07

1

問題是你正在調用release,然後你將屬性設置爲nil,在將它設置爲nil之前,它還會發送一個發佈到mTextLabel。當屬性被定義爲複製或保留時會發生這種情況。所有你需要的是下面的代碼。

[mTextLabel release]; 
mTextLabel = nil; 

編輯:

我想補充的是,在你的代碼中的init外的dealloc它是完全沒打電話self.mTextLabel = nil正常釋放,如果必要且無屬性的值。但是,建議NOT use the property in the init/dealloc calls。在這些情況下,您需要直接創建/釋放對象以避免訪問器的副作用。

+0

更好的是,使用'self.mTextLabel = nil'並讓屬性訪問器在適當的時候處理釋放。 – 2011-04-05 20:47:08

+0

我可以更新答案,但這是有點偏好。 – Joe 2011-04-05 20:49:31

+0

@Simon Whitaker在這裏閱讀例如http://stackoverflow.com/questions/4124049/dealloc-use-release-or-set-to-nil-for-properties我不會推薦投票,因爲你自己的最佳做法。 – Joe 2011-04-05 20:52:36

0

當您執行[self setMTextLabel:nil]時,該值已經發布。您不需要明確地發佈該值(除非您使用initcopy方法創建值,在這種情況下,只要您分配給self.mTextLabel,就應該立即釋放該值)。

請注意,retainCount has a return type of NSUInteger,所以永遠不可能是負面的。因此檢查以確保保留計數爲零而不是-1不起作用。

相關問題