gpt4 book ai didi

ios - 缓存图像和 UICollectionView

转载 作者:可可西里 更新时间:2023-11-01 03:27:27 29 4
gpt4 key购买 nike

我是 Objective-C 的新手,所以希望这一切都有意义。我已经从服务器下载图像,并在 collectionView cellForItemAtIndexPath: 方法的 ImageView 中显示它们。我面临的问题是图像似乎没有缓存。看起来每次重复使用一个单元格时,都会重新下载来自服务器的关联图像。

在我的 viewDidLoad 方法中,我正在创建一个 NSMutableDictionary:

imageDictionary = [[NSMutableDictionary alloc]initWithCapacity:50.0];

通过阅读文档和查看类似问题的答案,我认为这个加上下面的代码就足够了。我已经这样做了几天,我知道我遗漏了一些东西或者我没有掌握的概念。

#pragma mark - UICollectionView Data Source
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;{
NSLog(@"Begin retrieving photos");
return [self.photos count];
}

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
cell.imageView.image = nil;

if (cell.imageView.image == nil) {
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.photos objectAtIndex:indexPath.row] objectForKey:@"fullimage"]]];
UIImage *image = [UIImage imageWithData:data];
[imageDictionary setObject:image forKey:@"Image"];

dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [imageDictionary objectForKey:@"Image"];
[cell setNeedsDisplay];
});
});
}
return cell;
}

如有任何帮助,我们将不胜感激。提前致谢。

最佳答案

@yuf - 再次感谢您的指导。 NSCache 似乎让我得到了我想要的结果。这是正常工作的代码。如果有人遇到类似问题,您可以将以下内容与我原来的问题进行比较。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];

NSString *imageName = [[self.photos objectAtIndex:indexPath.row] objectForKey:@"fullimage"];
UIImage *image = [imageCache objectForKey:imageName];

if(image){

cell.imageView.image = image;
}

else{

cell.imageView.image = nil;

dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.photos objectAtIndex:indexPath.row] objectForKey:@"fullimage"]]];
UIImage *image = [UIImage imageWithData:data];

dispatch_async(dispatch_get_main_queue(), ^{

cell.imageView.image = image;

});

[imageCache setObject:image forKey:imageName];
});
}

return cell;
}

关于ios - 缓存图像和 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13852490/

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