2010-08-10 90 views
0

我有這個UITableView應用程序,一個基本的日記應用程序,在這個方法XCode說我有內存泄漏。建議首先泄漏的第一行是117「NSString * CellIdentifier」。 下來如果(細胞== ...,日記* diaryEntry,NSString *字符串日期。 那裏它說明方法返回一個+1保留計數擁有的對象 我試圖釋放單元格, stringDate ...什麼都沒有改變這個事實,所以我在想什麼/做錯了什麼?不知道爲什麼這是內存泄漏,請指教!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

// A date formatter for the time stamp static 

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
} 

Diary *diaryEntry = [diaryArray objectAtIndex:indexPath.row]; 

cell.textLabel.text = diaryEntry.diaryTitle; 

NSString *stringDate = [[DiaryDateFormatter alloc] convertDateToString:[diaryEntry diaryDate]]; 

cell.detailTextLabel.text = stringDate;  

[stringDate release]; 
return cell; 

}

回答

1

這行看起來有問題的:

NSString *stringDate = [[DiaryDateFormatter alloc] convertDateToString:[diaryEntry diaryDate]]; 
  1. 一旦你分配一個類的實例,你需要初始化它。如果convertDateToString:是一個初始化方法,那麼它應該重命名。然而,看起來convertDateToString:應該是一個類方法(這樣你就不必分配DiaryDateFormatter類的實例)。
  2. alloc方法總是爲您提供+1保留計數的對象。因此,您有責任釋放它。代碼的設置方式意味着您不能再訪問分配的對象以釋放它。

嘗試改變上面的代碼行成這樣:

DiaryDateFormatter *formatter = [[DiaryDateFormatter alloc] init]; 
NSString *stringDate = [formatter convertDateToString:[diaryEntry diaryDate]]; 
[formatter release]; 

而且,不釋放stringDate,因爲使用其名稱的方法並沒有得到它意味着你有所有權。

+0

我終於弄清楚了,到了它覺得這樣的年齡。但是現在我已經殺死了那個covertDateToSting的東西。剛剛造成了問題。在那之後問題解決了。 – 2010-08-11 06:09:10

-1

我看到的問題。您使用的Objective-C,你是沒有好處(像我一樣)

更重要的是,IIRC你應該使用自動釋放,而不是對細胞的分配,如果你是é會返回它?這就是我記得以前我跳船...