UICollectionView: How to handle updates both before and after view is loaded?

…衆ロ難τιáo~ 提交于 2019-12-11 13:56:36

问题


I'm having issues updating a collection view when receiving those updates via KVO.

e.g. for deletion I perform the following:

dispatch_async(dispatch_get_main_queue(), ^{
    NSUInteger index = [self.albumObjects indexOfObject:oldObject];
    NSIndexPath* indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [self.dataSource removeObjectAtIndex:index];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}

The above gives me the error:

attempt to delete item 0 from section 0 which only contains 0 items before the update

Ok... so lets remove from the data source afterwards then which then returns the following error:

dispatch_async(dispatch_get_main_queue(), ^{
    NSUInteger index = [self.albumObjects indexOfObject:oldObject];
    NSIndexPath* indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    [self.dataSource removeObjectAtIndex:index];
}

However I now get the following error instead:

Invalid update: invalid number of items in section 0.  The number of items contained in an existing section after the update (1) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).

So it seems I can't win? What am I doing wrong here?


回答1:


It seems the dispatch_async() causes the exception: when you modify your datasource (which adds your updater block to the end of the main queue), the item is already deleted when you try to update your collectionView.

What dataSource do you use? Is it managed manually? Or the the viewController is observing the datasource?



来源:https://stackoverflow.com/questions/21796571/uicollectionview-how-to-handle-updates-both-before-and-after-view-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!