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;
}
你可以刪除「我認爲」 - 這就是問題所在。 –
太棒了,它現在可以工作。謝謝! – Nyxynyx