0

tableviewcontroller的行为不正常。假设我向其中添加了 2 个对象:dogcat.

 - dog
 - cat

然后我删除猫。

 - dog

然后我添加第三个(此时为第二个)对象bird。单元格将填充cat而不是鸟。Bird 最终没有被存储在任何地方,我的列表结果如下:

 - dog 
 - cat

有谁知道这种行为可能是什么原因?我不是在我的代码中寻找特定错误,因为代码太多而无法显示。我希望你们可能知道我应该看看什么来解决这个问题。如果你们想以任何一种方式查看我的一些代码,请告诉我。谢谢。

编辑:所以每当删除某些内容时,我都会让控制台打印出数组中的所有对象。对象被正确地添加/删除到数组中,所以我的单元格似乎没有正确填充数据。

这里是cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        Employee* tempEmployee = [[[EmployeeStore store] employees] objectAtIndex:indexPath.row];
        NSString* label = [NSString stringWithFormat:@"N. %@   P. %@", tempEmployee.name, tempEmployee.pin];
        [[cell textLabel] setText: label];
    }
    return cell;
}

这是我用来删除的内容:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        NSMutableArray* employees = [[EmployeeStore store] employees];
        [[EmployeeStore store] removeEmployee:[employees objectAtIndex:indexPath.row]]; 
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

这是removeEmployee:我在上述方法中调用的 EmployeeStore 类:

-(void) removeEmployee:(Employee*)e{
    [context deleteObject:e];
    [employees removeObject:e];
}

编辑 2:我的应用程序正在利用核心数据来保存表格条目。当我关闭应用程序并再次运行它时,错误会自行修复(意味着它从上下文正确加载)。所以它从

 - dog 
 - cat 

达到预期:

 - dog
 - bird

好像更新不正常?

4

2 回答 2

0

将以下代码移到cellForRowAtIndexPath方法中的 if 条件之外

  Employee* tempEmployee = [[[EmployeeStore store] employees] objectAtIndex:indexPath.row];
  NSString* label = [NSString stringWithFormat:@"N. %@   P. %@", tempEmployee.name, tempEmployee.pin];
  [[cell textLabel] setText: label];

代码中的简单错误:仅在分配cellnew 时才设置文本,而不是在重用 a 时设置文本。cellcell

于 2013-06-24T04:38:25.847 回答
0

试试这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    Employee* tempEmployee = [[[EmployeeStore store] employees] objectAtIndex:indexPath.row];
    NSString* label = [NSString stringWithFormat:@"N. %@   P. %@", tempEmployee.name, tempEmployee.pin];
    [[cell textLabel] setText: label];

    return cell;
}
于 2013-06-24T04:34:26.467 回答