iOS - 从UITableView删除行

时间:2015-07-14 13:25:18

标签: ios objective-c uitableview

在遇到问题之前,我必须说明我已经检查了有关此问题的其他问题。

我在从UITableView中删除行时遇到问题。

我的应用程序允许用户选择一些联系人并在UITableview中显示他们的姓名和号码,并将这些信息保存在两个名为 people numbers 的可变数组中。

这是我用来删除单元格的方法。

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

//[tableView beginUpdates];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
   //[numbers removeObjectAtIndex:indexPath.row];
   //[people removeObjectAtIndex:indexPath.row];
   [self.tableData removeObjectAtIndex:indexPath.row];
   [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];

}
//[tableView endUpdates];
[tableView reloadData];}

这是我的数据设置

#import <UIKit/UIKit.h>
@import AddressBook;
@import AddressBookUI;

@interface addedContacts : UIViewController <UITextFieldDelegate, ABPeoplePickerNavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource>{
NSMutableArray* people;
NSMutableArray* numbers;
IBOutlet UITableView *tableview;
}
@property (strong, nonatomic) IBOutlet UITableView *mTV;
- (IBAction)addPerson:(id)sender;
- (IBAction)editButton:(id)sender;
@property (nonatomic, strong) NSMutableArray *tableData;

@end

我在.m文件的开头定义 tableview IBOutlet的属性。

-(void)viewDidLoad{
[super viewDidLoad];
tableview.delegate = self;
tableview.dataSource = self;}

这是我得到的例外;

2015-07-14 16:16:06.207 MyTestApp[716:607] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2935.137/UITableView.m:1368
2015-07-14 16:16:06.491 MyTestApp[716:607] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
  The number of rows contained in an existing section after the update (6) must be equal to the number of rows contained in that section before the update (6),
 plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

那么,我哪里做错了?

如果需要,我可以提供第一个抛出的调用堆栈或更多代码。

更多信息

-(NSInteger) tableView:(UITableView*) tableView numberOfRowsInSection:(NSInteger)section
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
numbers = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:@"numbers"]];
return [numbers count];
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}

2 个答案:

答案 0 :(得分:2)

您应该为self.tableData.count方法返回numberOfRowsInSection。截至目前,您不会从numberOfRowsInSection返回的数据源中删除,因此您的计数已关闭。

您也不应该访问那里的NSUserDefaults。在viewDidLoad中,您应该从NSUserDefaults加载所有内容,允许用户进行更改并更新数据。然后,当您离开视图时,将所有内容保存回NSUserDefaults

答案 1 :(得分:1)

在致电reloadData后,您不应该直接致电deleteRowsAtIndexPaths。这可能会导致动画冲突,这可能是导致当前崩溃的原因。