我无法缓存并显示缓存的图像。 这是一个包含大量图像的集合视图。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell";
CollectionViewCell *cell = (CollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImage *imageMP = [_imageCache objectForKey:[self getImage:indexPath.row]];
NSLog(@"looking for \"%@\"",[self getImage:indexPath.row]);
if (imageMP) {
NSLog(@"found it!");
cell.img_pic.image = imageMP;
}else{
//display loading pic so long
cell.img_pic.image = [UIImage imageNamed:@"photo1.png"];
[self.queue addOperationWithBlock:^{
UIImage *image = [self getActualImage:indexPath.row];
if (image) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.img_pic.image = image;
}];
[_imageCache setObject:image forKey:[self getImage:indexPath.row]];
NSLog(@"saving as \"%@\"",[self getImage:indexPath.row]);
}
}];
}
它正确加载和显示图像,问题在于保存到缓存然后从缓存中显示。
NSLog到控制台的输出如下
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
saving as "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
saving as "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
saving as "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg"
它从未正确显示缓存的图像,否则会打印“找到它!”
我做错了什么?
答案 0 :(得分:1)
使用JMCache(https://github.com/jakemarsh/JMImageCache)然后使用以下代码
[cell.img_pic.image setImageWithURL:[NSURL URLWithString:imageUrl] placeholder:[UIImage imageNamed:@"laoding.png"]];
答案 1 :(得分:0)
这解决了问题。
_imageCache = [[NSCache alloc] init];
我忘了分配并初始化NSCache。