从tableView中删除记录 - 初学者

时间:2011-10-13 22:38:37

标签: iphone objective-c xcode

我需要从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的{​​{1}}填充的,那么如何删除记录并更新我的表格视图?

3 个答案:

答案 0 :(得分:2)

您不需要第一次endUpdates来电。

beginUpdatesendUpdates之间,您还应该从peopleList数组中删除该对象,这样当您调用{{1}时,表视图和数组都会减少1个元素}。除此之外,它应该工作正常。

答案 1 :(得分: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];

        ...
    }   
...

答案 2 :(得分: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];
相关问题