我在缓存和显示缓存的图像时遇到问题。这是一个包含大量图像的集合视图。
-(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"
它永远不会正确显示缓存的图像,否则会打印“找到它!”
我究竟做错了什么?