2011-10-13 56 views
2

我需要从tableView中删除一行,并且tableview应该得到更新,我该如何编程?从tableView删除记录 - 初学者

我到目前为止的工作;

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    { 

     [tableView endUpdates];  
     [tableView beginUpdates]; 
///?????????? 

     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     [tableView endUpdates]; 

    } 
} 

我的表是使用NSArray称为peopleList稀少,所以,我怎么能删除记录和更新我的表视图?

+0

你最终解决了这个问题吗? – bryanmac

回答

2

您不需要第一个endUpdates调用。

之间beginUpdatesendUpdates你也应该从你的peopleList数组中删除的对象,所以,无论是表视图和阵列有少1元,当你调用endUpdates。除此之外,它应该可以正常工作。

+0

SO是这样的吗? [tableView beginUpdates]; \t \t // DELETE FROM LIST [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView endUpdates]; – thar

+0

我还得到了这个异常'终止应用程序,由于未捕获异常'NSInternalInconsistencyException',原因:'无效更新:在0节中的行数无效。更新(4)后现有节中包含的行数必须等于在更新之前包含在该部分中的行数(4),加上或减去从该部分插入或删除的行数(0插入,1删除)。“任何线索? – thar

+0

您需要从'peopleList'中删除对象,并在其中写入'DELETE FROM LIST'来修复该异常。 – darvids0n

0

在您的表视图的开始/结束更新块中,您需要将您的peopleList复制到可变数组,删除记录,然后将peopleList设置为已更改数组的不可变副本。

[tableView beginUpdates]; 

// Sending -mutableCopy to an NSArray returns an NSMutableArray 
NSMutableArray *peopleListCopy = [self.peopleList mutableCopy]; 

// Delete the appropriate object 
[peopleListCopy removeObjectAtIndex:indexPath.row]; 

// Sending -copy to an NSMutableArray returns an immutable NSArray. 
// Autoreleasing because the setter for peopleList will retain the array. 
// -autorelease is unnecessary if you're using Automatic Reference Counting. 
self.peopleList = [[peopleListCopy copy] autorelease]; 

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

[tableView endUpdates]; 
1

我会推荐使用NSMutableArray作为存储而不是NSArray。

刚刚更新了存储空间 - 对于NSMutableArray(而不是您提到的NSArray),您只需在调用removeObjectsAtIndex之前调用removeObjectAtIndex。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    { 

     ... 

     // Delete the row from the data source 
     NSLog(@"delete section: %d rol: %d", [indexPath indexAtPosition:0], [indexPath indexAtPosition:1]); 
     [_items removeObjectAtIndex:[indexPath indexAtPosition:1]]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

     ... 
    } 
...