我想從文檔目錄加載圖像到UICollectionView
。它的工作原理:平穩,快速....(大聲笑)。但我得到一個問題:當我打電話[collectionView reloadData]
,圖像閃爍(一次)。這裏是我的代碼:從文檔目錄異步加載圖像到UICollectionView
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView_ cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = NSStringFromClass([AFMyRecentCollectionViewCell class]);
AFMyRecentCollectionViewCell *cell = (AFMyRecentCollectionViewCell*)[collectionView_ dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
AFMyRecentObject *recent = [[AFRecentManager sharedInstance].arrayRecent objectAtIndex:indexPath.row];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [self databasePathWithPathComponent:[NSString stringWithFormat:@"%@.jpg", recent.id_film]];
if ([fileManager fileExistsAtPath:filePath] == YES) {
image = [UIImage imageWithContentsOfFile:filePath];
}
dispatch_async(dispatch_get_main_queue(), ^{
if (image) {
cell.imageView.image = image;
} else {
cell.imageView.image = [UIImage imageNamed:@"loadding.png"];
}
});
});
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
- (NSString *)databasePathWithPathComponent:(NSString*)pathComponent {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:pathComponent];
return path;
}
順便說一句,你在技術上應該確保了'cell'還沒有被重新用於另一個'NSIndexPath' 'UIImage'被實例化的時間。很可能,因爲你從本地存儲中檢索,這不太可能是個問題,但是如果你要發起任何網絡請求,那麼在蜂窩網絡上快速滾動時突然變成一個非常實際的問題。因此,要非常小心地使用上述模式,除非您確信在異步更新過程中單元格不能重新使用。 – Rob