从tableView返回单元格时出错

时间:2012-09-25 18:15:57

标签: iphone ios uitableview

我在ios中使用表视图相对较新。我正在尝试使用不同的视图编辑数据并更新原始视图中的值。我设置了单元格标识符并编写了以下代码

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  
{ 
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NameIdentifier";
    Item *currentItem=[self.items objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
     cell.textLabel.text=currentItem.itemName;    
     return cell;
    }

但是我收到以下错误:

NSInternalInconsistencyException', 
reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

1 个答案:

答案 0 :(得分:2)

您需要检查并确保dequeueReusableCellWithIdentifier能够将单元格出列。它崩溃了,因为它不会每次都返回一个单元格。如果您无法将可重复使用的单元格出列,则需要创建一个新单元格。您的代码应如下所示:

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

        static NSString *CellIdentifier = @"NameIdentifier";
        Item *currentItem=[self.items objectAtIndex:indexPath.row];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil)  
           cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];

         // Configure the cell...
         cell.textLabel.text=currentItem.itemName;    
         return cell;
        }
相关问题