我有一个 UICollectionView,它由子类 UICollectionViewCells 组成。
这些单元格上有向 API 发出异步请求的按钮。在一种情况下,我有一个“心脏”按钮。点击此按钮将禁用按钮并异步进行 API 调用并传入一个块以用作回调。当调用成功返回时,按钮将更新为不同的状态。
问题是,当调用块中的代码时,对单元格的引用似乎会丢失或更改。所以,坏事发生了,比如当单元格滚动离开屏幕时,按钮的状态永远不会更新,并且只要重新使用该单元格,按钮就会保持禁用状态。
这里的最佳做法是什么?
- (void)didTapHeart:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:currentTouchPosition];
__block MyObject *object = [myObjects objectAtIndex:indexPath.row];
__block CollectionViewCell *cell = (CollectionViewCell *)[sender superview];
cell.btnHeart.enabled = NO;
[[ApiSingleton defaultApi] like:object success:^{
dispatch_async(dispatch_get_main_queue(), ^{
cell.btnHeart.enabled = YES;
object.isLiked = YES;
object.likeCount++;
[cell setLiked:YES];
});
} failure:^(NSDictionary *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[cell setLiked:NO];
cell.btnHeart.enabled = YES;
object.isLiked = NO;
});
}];
}