我对 Objective-C 很陌生,所以希望这一切都有意义。我已经从服务器下载了图像,并在该collectionView cellForItemAtIndexPath:
方法的图像视图中显示了它们。我面临的问题是图像似乎没有缓存。看起来每次重复使用一个单元格时,都会重新下载来自服务器的相关图像。
在我的 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;
}
任何帮助将不胜感激。提前致谢。