我有一個問題。在我的.h:是否有必要在dealloc中釋放此對象?
NSString *string;
@property(nonatomic, retain)NSString *string;
在我的.m:
string=[NSString stringWithFormat:@"%@", otherStringWithValue];
好吧, 「stringWithFormat」 是一個自動釋放方法。我需要在dealloc中釋放「string」?
我有一個問題。在我的.h:是否有必要在dealloc中釋放此對象?
NSString *string;
@property(nonatomic, retain)NSString *string;
在我的.m:
string=[NSString stringWithFormat:@"%@", otherStringWithValue];
好吧, 「stringWithFormat」 是一個自動釋放方法。我需要在dealloc中釋放「string」?
如果你聲明的字符串是上述代碼中屬性的一部分,那麼是的,即使你必須初始化它。所有權仍然是你的謹慎。
該代碼將引入內存泄漏,因爲stringWithFormat返回自動釋放的對象,你有保留的字符串,所以當你指定字符串stringWithFormat的值將提供新的自動釋放object.But任何記憶你保留字符串仍然存在,因爲它的保留計數仍然是1,所以它不會被釋放。但是如果你試圖釋放字符串,它會崩潰,因爲分配後它將包含autorelease對象。
只有self.string = ....會保留你的stringWithFormat。
所以你不需要釋放它。但要注意,你的字符串將會被釋放,並且你的應用程序在以後嘗試訪問它時會崩潰。如果你想保持你的字符串,以便使
self.string = .....
,並釋放它的dealloc上
的屬性應用於唯一的財產。 無法直接訪問屬性。它可以通過「。」訪問。只要。
所以,當你寫,
string=[NSString stringWithFormat:@"%@", otherStringWithValue];
您正在訪問的變量。所以,不會保留任何內容。另外,stringWithFormat
將返回自動釋放對象。所以,不需要在dealloc中釋放它。然而,你不能在範圍之外訪問這個變量,因爲你不知道它何時會被釋放。
如果你寫,
self.string=[NSString stringWithFormat:@"%@", otherStringWithValue];
您正在訪問屬性和值將被保留。所以,你必須在dealloc方法中釋放它。
說真的。這意味着您不再需要擔心保留/釋放(儘管您不必擔心參考週期,無論如何您都必須擔心)。
如果您沒有使用ARC,那麼上面的代碼會崩潰,因爲您沒有對該字符串進行「所有權」(通過保留它)。無論正確保留它:
[string release];
string=[[NSString stringWithFormat:@"%@", otherStringWithValue] retain];
或者使用setter,它(如果是自動生成的話)將正確地保留它:
self.string=[NSString stringWithFormat:@"%@", otherStringWithValue];
在-dealloc
,那麼你必須釋放實例變量,或者你可以只使用setter方法(它會自動釋放你):
self.string = nil;
ARC之前,我的經驗法則是幾乎總是使用屬性語法,因爲它只是做正確的事情。
,而不是這樣的:
string=[NSString stringWithFormat:@"%@", otherStringWithValue];
做到這一點:
self.string=[NSString stringWithFormat:@"%@", otherStringWithValue];
現在,你需要釋放字符串中的的dealloc。雖然,+ stringWithFormat返回autorelased對象,但你已經聲明瞭保留屬性,所以你有責任釋放它。
誰曾經低估過,你能解釋爲什麼? –
每一句話都是完全錯誤的。 1)不會有內存泄漏 - 會有相反的,一個懸掛的指針2)屬性被聲明爲保留是無關的,因爲他根本沒有使用屬性3)字符串是autoreleased,這意味着它會得到釋放和釋放(因爲沒有人保留它)一段時間後,當你試圖發送任何消息到該變量的對象,你會得到未定義的行爲,因爲指針不再指向有效的對象 – user102008
好吧我同意你的評論,將有懸掛指針。但現在我的問題是財產宣佈零售是無關緊要的,因爲他根本沒有使用該屬性,爲什麼?如果是這樣的話,然後分配字符串值,如果我執行[self.string釋放]在dealloc,然後根據你不應該墜毀,因爲兩者都不同。 –