2011-10-07 34 views
0

我目前正在使用書籍學習UITableViewCell。爲了在滾動時重用單元格,作者要求修改原始代碼以包含if()語句以檢查特定重用標識符的單元是否存在。但是,在添加if()語句之後,Xcode會在if(!cell)內部的行中引發Unused variable 'cell'的警告。在運行代碼時,出現錯誤Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'出錯了嗎?if()被引入時未使用的變量

原始代碼

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

UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
               reuseIdentifier:@"UITableViewCell"] autorelease]; 
Possession *p = [[[PossessionStore defaultStore] allPossessions] objectAtIndex:[indexPath row]]; 
[[cell textLabel] setText:[p description]]; 

return cell; 
} 

修改代碼

- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
// Check for reusable cell first, use that if it exists 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 

// If there is no reusable cell of this type, create a new one 
if (!cell) { 
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                reuseIdentifier:@"UITableViewCell"] autorelease]; 
} 

Possession *p = [[[PossessionStore defaultStore] allPossessions] objectAtIndex:[indexPath row]]; 
[[cell textLabel] setText:[p description]]; 

return cell; 
} 

回答

6

我認爲你必須放下UITableViewCell *條件塊內。否則,你會在塊內聲明一個新的cell變量並將其扔掉,而不是分配給上面聲明的單元格。 (沒有編譯器提醒你這個問題?)總體邏輯應該是:

UITableViewCell *cell = /* try to get a cached one */ 
if (cell == nil) { 
    cell = /* there was no cached cell available, create a fresh one */ 
} 
/* …more code… */ 
/* and finally return the created cell */ 
return cell; 
+0

你可以刪除「我認爲」 - 這就是問題所在。 –

+0

太棒了,它現在可以工作。謝謝! – Nyxynyx