1

コレクションビューを管理するためのこのコードがあります

- (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];
}

この場合、コレクションビューに画像が完全に取り込まれていない場合、アクションを戻すと次のエラーが発生します。

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

問題はどこだ?

4

1 に答える 1

1

ビューコントローラーをポップすると、ダウンロードはまだ進行中です。したがって、非同期コールバックが実行されると、存在しない で[collectionView reloadItemsAtIndexPaths...]呼び出されます。collectionView

collectionView != nilコールバック ブロックの最初の行で、return;それが nil であるかどうかを確認する必要があります。

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 に答える