static Object lock = [Object alloc] init];
int count = _dataArray.count;
for(int i = 0; i < count ; i ++ )
{
UploadModel *model = _dataArray;
UploadManager *manager = [[UploadManager alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[manager uploadImagesWithSelecteArray: model success:^{
// 上传成功回调 删除_dataArray中的数据
//为什么要加个锁,因为每个任务结束的时间是不一样的,block也会开子线程,你获得了某个index后,cpu青睐了其他线程,然后执行了[_dataArray removeObject: model],你之前获得的index就是错误的index,所以你要加个锁,锁住这块代码,等这块代码执行完,才会放开这个锁.这样你上传是异步的,成功之后删除数组,更新Ui都是同步的,这样不会出现异步造成的错误
@synchronized (lock) {
NSInteger index = [_dataArray indexOfObject: model];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
[_dataArray removeObject: model];
// 删除对应的Cell
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
});
}
} failure:^{
NSLog(@"上传失败提示");
}];
});
}
网友评论