我是很新,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;
}
任何帮助将不胜感激。 提前致谢。