簡體   English   中英

TableViewController無法正確刪除單元格?

[英]TableViewController not properly deleting cells?

我的tableviewcontroller行為不正常。 可以說我添加了兩個對象: 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];
    }
}

這是上述方法中調用的EmployeeStore類中的removeEmployee: ::

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

編輯2:我的應用程序正在利用核心數據來保存表條目。 當我關閉應用程序並再次運行時,該錯誤會自行修復(這意味着它已從上下文正確加載)。 所以它來自

 - dog 
 - cat 

達到預期目的:

 - dog
 - bird

似乎更新不當?

嘗試這樣:

- (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;
}

將以下代碼移至cellForRowAtIndexPath方法的if條件之外

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

代碼中的簡單錯誤:僅當分配了新的cell時才設置cell文本,而不是在重用cell時才設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM