Ste*_*ven 5 uitableview grand-central-dispatch ios
我正在尝试将远程站点的缩略图加载到UITableView上.我想以异步方式执行此操作,并且我想为缩略图图像实现穷人的缓存.这是我的代码片段(我将在下面描述有问题的行为):
@property (nonatomic, strong) NSMutableDictionary *thumbnailsCache;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
// ...after obtaining the cell:
NSString *thumbnailCacheKey = [NSString stringWithFormat:@"cache%d", indexPath.row];
if (![[self.thumbnailsCache allKeys] containsObject:thumbnailCacheKey]) {
// thumbnail for this row is not found in cache, so get it from remote website
__block NSData *image = nil;
dispatch_queue_t imageQueue = dispatch_queue_create("queueForCellImage", NULL);
dispatch_async(imageQueue, ^{
NSString *thumbnailURL = myCustomFunctionGetThumbnailURL:indexPath.row;
image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:thumbnailURL]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:image];
});
});
dispatch_release(imageQueue);
[self.thumbnailsCache setObject:image forKey:thumbnailCacheKey];
} else {
// thumbnail is in cache
NSData *image = [self.thumbnailsCache objectForKey:thumbnailCacheKey];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:image];
});
}
Run Code Online (Sandbox Code Playgroud)
所以这是有问题的行为:
加载UITableView时,缩略图不会显示在初始单元格集上.只有当一个单元格移出屏幕时,才会重新开启,缩略图会显示出来.
缓存根本不起作用.据我所知,它无法将缩略图完全保存到缓存中.也就是说,这一行失败了:
[self.thumbnailsCache setObject:image forKey:thumbnailCacheKey];
正在为每个单元格创建/释放GCD队列.此外,队列名称每次都相同.这是不好的做法吗?
我很感激你们指出你看到的任何错误,甚至是任何一般的方法评论.谢谢.
已解决:我添加了对reloadRowsAtIndexPaths的调用,现在缩略图图像加载到显示的初始行
解决:它失败的原因是因为它在另一个线程完成设置该对象之前将图像对象添加到字典中.我创建了一个实例方法来将对象添加到属性字典中,这样我就可以从块内部调用它,确保在设置图像对象后添加它.
1) 没有显示初始图像的原因是因为单元格是用 image = nil 渲染的,因此它智能地隐藏了图像视图。
2)您是否尝试将这条线移到您的街区内?
[self.thumbnailsCache setObject:image forKey:thumbnailCacheKey];
Run Code Online (Sandbox Code Playgroud)
3)这只是区分要调试的队列,并从控制台获取信息的一种方法,如果您的应用程序崩溃,那么您可以看到队列的名称。如果您对此具有相同的名称,这不应该是问题,因为它执行相同的操作。如果您有相同的逻辑,您不会想在另一个表视图中使用此名称。
归档时间: |
|
查看次数: |
5900 次 |
最近记录: |