简体   繁体   中英

UICollectionView crash when deleting last item

I am trying to update the uicollection view whenever I delete a item. All the cells are deleting fine but if I delete the last cell in that collection view App crashes and I have put

[self.collectionview performBatchUpdates:^{
        [postarray removeObjectAtIndex:indexPath.item];
        [self.collectionview deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:1]]];
    } completion:^(BOOL finished) {}];

The error I got is 'NSRangeException', reason: ' * -[__NSArrayI objectAtIndex:]: index 17 beyond bounds [0 .. 16]' . Even array and collection view item starts at same index,I got this message

I was getting the same error message with the same lines of code, and it turned out it had nothing to do with the UICollectionView data source, but with a parallel array in another part of the app that updated its contents after but not its active index after the delete.

To find errors like this, enable Exception breakpoints: NSRangeException when deleting last UICollectionViewCell

Just inverse your two lines. You need to remove cell before to remove your object.

[self.collectionview performBatchUpdates:^{
        [self.collectionview deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:1]]];
        [postarray removeObjectAtIndex:indexPath.item];
    } completion:^(BOOL finished) {}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM