hpi*_*que 5 iphone uitableview grand-central-dispatch ios
我正在使用Grand Central Dispatch来UITableViewCell异步加载图像.这种方法很有效,除了在一些边界情况下,单元格被重用,而前一个块加载了错误的图像.
我当前的代码如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *imagePath = [self imagePathForIndexPath:indexPath];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
dispatch_sync(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
[cell setNeedsLayout];
});
});
return cell;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,GCD队列无法停止.那么如何防止这种边界情况呢?或者我应该使用其他东西而不是GCD来解决这个问题?
我所做的是将NSOperationivar 添加到单元格中。该操作负责获取、加载和创建图像。完成后,它会对单元执行 ping 操作。当/如果单元出队时,如果操作尚未完成,则操作将被取消并销毁。时取消的操作测试-main。将图像传递到单元格后,单元格会放弃操作并使用该图像。
| 归档时间: |
|
| 查看次数: |
980 次 |
| 最近记录: |