2010-10-10 11 views
0

很抱歉的長標題特定的順序不同UITableViewCells的。實質上,我想完成日曆應用程序爲事件詳細信息所做的相同事情。 第一個單元格顯示事件的標題和日期。第二個顯示一個警報,如果有的話,否則註釋,如果有的話,或者沒有其他的,如果這些字段都不存在。變動數與像日曆應用

我現在做的方式是一個很長的,如果條件的cellForRowAtIndexPath:

if(indexPath.row == 0) { 
    TitleCell *titlecell = [[TitleCell alloc] init]; 
    // config cell to do title here, always 
    return titlecell; 
} else if (indexPath.row == 1 && foo) { 
    FooCell *foocell = [[FooCell alloc] init]; 
    // config cell to show foo, if it exists 
    return foocell; 
} else if (indexPath.row == 1 && bar) { 
    BarCell *barcell = [[BarCell alloc] init]; 
    // foo doesn't exist, but bar, so show bar in cell 1 
    return barcell; 
} // etc etc 

這是十分可怕的,因爲我在,如果和回報創造細胞,靜態分析儀告訴我,每個其中之一是潛在的泄漏。沒有別的,因爲我需要覆蓋所有場景,並且還會提供有關可能不會返回任何內容的方法的警告。

有沒有更好的辦法,使這一清潔,不給我的警告?

謝謝!

克里斯托夫

回答

2

該警告是因爲您泄漏內存,您必須自動釋放該單元格:TitleCell *titlecell = [[[TitleCell alloc] init] autorelease];。也有是沒有return語句,因爲你沒有elseif塊做的機會。

這裏是做的另一種方式:


// Call this beforehand 
- (void)loadTable { 
    // Since we are not using objects, we need to use a non-retaining array 
    // A better way of doing this would be with delegates or NSInvocations 
    array = (NSMutableArray*)CFArrayCreateMutable(NULL, 0, NULL); 
    [array addObject:(id)@selector(buildTitleCell)]; 
    if (foo) 
    [array addObject:(id)@selector(buildFooCell)]; 
    if (bar) 
    [array addObject:(id)@selector(buildBarCell)]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.row < array.count) { 
    SEL selector = (SEL)[array objectAtIndex:indexPath.row]; 
    return [self performSelector:selector]; 
    } 
    return nil; 
} 

- (UITableViewCell*)buildTitleCell { 
    TitleCell *titlecell = [[[TitleCell alloc] init] autorelease]; 
    // config cell to do title here, always 
    return titlecell; 
} 
... 

編輯:固定爲每@克里斯托夫的評論

+0

謝謝,儘管如果Foo不存在,我不確定這會起作用。在這種情況下,Bar應該位於單元格1中。或者我錯過了什麼? – Christoph 2010-10-10 05:10:32

+0

你說得對,我現在修好了。 – Aleph7 2010-10-10 06:49:23

+0

由於雙方你指出我,其實,內存泄漏。我選擇這個作爲其代碼的公認答案。 – Christoph 2010-10-10 19:32:12

1

鏘是正確的,當它說,你正在泄漏內存 - 該UITableView保留UITableViewCell是你們等給它,所以你應該在cellForRowAtIndexPath自動釋放他們。

而不是使用if statments的,我想你應該使用switch

+0

哇,你是對的。一定是錯過了Xcode模板中的autorelease,只是在我改變了東西的時候沒有把它放回去。謝謝! – Christoph 2010-10-10 04:56:25