gpt4 book ai didi

ios - 异步下载 1000 张图像并进行缓存,但会出现内存问题

转载 作者:行者123 更新时间:2023-11-28 18:53:57 24 4
gpt4 key购买 nike

我有一个代码可以下载大约 1000 张图像,还可以使用 NSCache 执行缓存并在 UICollectionView 中显示图像。它可以工作,但是当 UICollectionView 滚动得非常快并且互联网速度很慢时,会收到内存警告。那么这里的问题是什么?以下是我的代码:提前致谢。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ProductCollectionViewCell *cell = (ProductCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

//set image,title of product
cell.productLabel.text = [self.productNameArray objectAtIndex:indexPath.row];
UIImage *image = [self.imgCache getCachedImageForKey:[self.imgUrlArray objectAtIndex:indexPath.row]];
if (image.size.width>0) {
[cell.productImage setImage:image];
}
else {
[cell.productImage setImage:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.imgUrlArray objectAtIndex:indexPath.row]]];
UIImage *img = [UIImage imageWithData:imgData];
[cell.productImage setImage:nil];
dispatch_async(dispatch_get_main_queue(), ^{
if (imgData!=nil) {
[cell.productImage setImage:img];
[self.imgCache cacheImage:img forKey:[self.imgUrlArray objectAtIndex:indexPath.row]];
if ([self.imgDataArray count] <= [self.productNameArray count]) {
[self.imgDataArray addObject:imgData];
}
}
});
if ([self.imgDataArray count] == [self.productNameArray count]){
[self.productsView.collectionView reloadData];
}
});
}
return cell;
}

最佳答案

您可以使用这个 SDWebImage

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

关于ios - 异步下载 1000 张图像并进行缓存,但会出现内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com