美文网首页
解决删除Cell/item时removeObjectAtInde

解决删除Cell/item时removeObjectAtInde

作者: Jerry_WJ | 来源:发表于2018-05-16 17:50 被阅读78次

    解决collectionView/tableView使用deleteItemsAtIndexPaths:方法带动画删除item/cell时可能引起removeObjectAtIndex:崩溃问题

    解决方法:

    参考链接:https://www.jianshu.com/p/f89ee2802679

    思路:通过调用collectionView或tableView的performBatchUpdates:方法来处理删除逻辑后,在completion block中调用reloadData:已刷新item,可防止崩溃

    代码实例:

    // 官方解释
    - (void)performBatchUpdates:(void (NS_NOESCAPE ^ _Nullable)(void))updates completion:(void (^ _Nullable)(BOOL finished))completion; // allows multiple insert/delete/reload/move calls to be animated simultaneously. Nestable.
    
    // 适用场景,cell的点击事件通过block回调的情形,不然会造成indexPath值错乱,因为调用deleteItemsAtIndexPaths:方法时,只会调用numberOfItemsInSection刷新一下item的数量,并不会调用cellForItemAtIndexPath来刷新数据,(因为只是删除,item的内容不会变,只会动一下位置)造成崩溃。
    
    // 解决方案:(核心代码)
    
    [collectionView performBatchUpdates:^{
    
            // 首先删除数据源
        [self.dataAry removeObjectAtIndex:indexPath.row];
            // 删除item
        [collectionView deleteItemsAtIndexPaths:@[indexPath]];
    
    }completion:^(BOOL finished){
    
        [collectionView reloadData];// reloadData 保证item indexPath的一一对应。
    
    }];
    

    相关文章

      网友评论

          本文标题:解决删除Cell/item时removeObjectAtInde

          本文链接:https://www.haomeiwen.com/subject/gmkmdftx.html