tableView建立好友列表

遇到的问题主要是使用插入和删除的两个方法时出现报错

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 3. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (7 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

原因网上有说用[tableView beginUpdates];[tableView endUpdates];把插入和删除的那句话包起来的,但是我实际操作了一下,发现不是因为这个。
主因在于insertRowsAtPathsdeleteRowsAtIndexPaths这两个方法自己是会跑reloaddData的,我们不能手动写reloadData
另外,以前做的时候说更新数据源是更新的模型数据,因为以前说“删除cell”就是真的左划然后点删除,现在用这个方法实现”删除cell”实际上并不是要把数据删掉,不需要动模型数据。所以直接在numberOfRowsInSection中判断一下选项卡是开还是关,然后返回0或者联系人个数的cell就行了。

点击按钮响应部分
其中self.dataTestArr是用来测试的,大概是@[@3,@5,@6,@7]这种,意思就是有四个好友分组,每组里面的好有个数分别是3 5 6 7。

//获得要插入的cell的位置(indexPath)
//利用btn.tag-base4ButtonTag获取section,因为btn的tag是用section加上常数base4ButtonTag得来的
    NSMutableArray *indexPathArr = [NSMutableArray array];
    for (int i = 0; i<[self.dataTestArr[btn.tag-base4ButtonTag] intValue]; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:btn.tag-base4ButtonTag];
        [indexPathArr addObject:indexPath];
    }
//通过自定义的btn类中的属性来判断当前点击时,是开启还是关闭
    if (btn.isOpen) {
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
    }
    else{
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];

数据源的处理

/*重点在于,用header做的分组卡,而header是不能被取到的
所以只能在一开始的时候根据选项卡的个数初始化一个数组,数组里面放的全是初始的"close"字符
(注意到数组里面不能直接存放BOOL或者int,而转换后,比如5转成NSNumber后如果不转回int,在跟诸如1、2、3、4、5、6比较会一直是true)
*/

   //1.viewDidLoad中初始化数组,用来记录section有没有打开
    _arr4isOpen = [NSMutableArray array];
    for (int i = 0; i

你可能感兴趣的:(tableView建立好友列表)