1

我有这个代码来管理一个collectionview

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return  1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [images count];
}

- (PhotoCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    PhotoCell *cell = [gridPhoto dequeueReusableCellWithReuseIdentifier:@"photocell" forIndexPath:indexPath];

    NSMutableDictionary *record = [images objectAtIndex:[indexPath row]];
    if ([record valueForKey:@"actualImage"]) {
        [cell.image setImage:[record valueForKey:@"actualImage"]];
        [cell.activity stopAnimating];
    } else {
        dispatch_async(imageQueue_, ^{
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[record objectForKey:@"url"]]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [record setValue:[UIImage imageWithData:imageData] forKey:@"actualImage"];
                [collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
            });
        });
    }

    return cell;
}

如果 imageQueue_ 完成它的工作并填充整个集合视图,它就可以正常工作;当我退出视图时我遇到了问题

- (IBAction)back:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

在这种情况下,如果 collectionview 没有全部填充图像,则在执行返回操作时会出现此错误:

[PhotoGalleryViewController numberOfSectionsInCollectionView:]: message sent to deallocated instance 0x1590aab0

问题出在哪里?

4

1 回答 1

1

当您弹出视图控制器时,下载仍在进行中。因此,当执行异步回调时,您[collectionView reloadItemsAtIndexPaths...]会在collectionView不再存在的 a 上调​​用。

collectionView != nil您应该在回调块的第一行检查它,return;如果它为零:

dispatch_async(dispatch_get_main_queue(), ^{
    if (collectionView == nil)
        return;

    [record setValue:[UIImage imageWithData:imageData] forKey:@"actualImage"];
    [collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
});
于 2014-02-12T10:40:27.947 回答