异步提取已完成:仍在显示单元吗? [英] Asynchronous Fetch completed: Is cell still being displayed?

查看:69
本文介绍了异步提取已完成:仍在显示单元吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的一次采访中,有人问我诸如#9 是关于将图片异步下载到表格视图单元格中的问题.我了解在cellForIndexPath中异步调用它的必要性,但是我对如何在异步调用完成后如何查看是否仍在查看该单元格感到困惑(请参阅下面的项目符号3摘录).换句话说,在异步调用之后,如何确定我正在为其获取数据的表单元格是否仍在视图中.

During a recent interview, I was asked a scenario like #9 of these common interview questions regarding downloading images asynchronously into a table view cell. I understand the necessity for it to be called in cellForIndexPath and asynchronously but I was stumped as to how to check to see if the cell is still in view after the async call is complete (see the bullet #3 excerpt below). In other words, after an async call, how can I determine whether the table cell I was fetching data for is still in the view.

为某个单元下载图像后,我们需要检查该单元是否仍在视图中,或者是否已被另一块重复使用数据的.如果已被重复使用,则我们应该丢弃该图像,否则,我们需要切换回主线程来更改图像在单元格上.

When the image has downloaded for a cell we need to check if that cell is still in the view or whether it has been re-used by another piece of data. If it’s been re-used then we should discard the image, otherwise we need to switch back to the main thread to change the image on the cell.

推荐答案

您应该开始使用回调机制在后台下载图像,该机制可以决定在加载图像后是否仍应显示该图像.

You should start downloading your image in the background with a callback mechanism that can decide if the image should still be displayed after it's been loaded.

一种选择是继承 UIImageView UITableViewCell 并存储对图像的 NSURL 的引用.然后,在调用回调时,您可以检查图像视图或单元格的缓存URL是否是您拥有的图像之一,然后决定是否显示它.

One option would be to subclass UIImageView or UITableViewCell and store a reference to the NSURL of the image. Then, when your callback is called, you could check if the image view or the cell's cached URL is the one of the image you have, and decide to display it or not.

我不会推荐:

  • 依靠视图的标记,因为它需要某种NSURL和整数之间的关联表,这需要一个管理器对象,并且不利于代码的可重用性
  • 依靠单元格的indexPath,因为在发生网络请求时可能会发生表更新或单元格被其他索引路径重用

NSHipster的关联对象中介绍了更高级的选项:

A more advanced options is described in Associated Objects, by NSHipster:

在扩展内置类的行为时,可能有必要跟踪其他状态.这是关联对象的教科书用例.例如,AFNetworking使用其UIImageView类别上的关联对象来存储请求操作对象,该请求操作对象用于以特定URL异步获取远程图像.

When extending the behavior of a built-in class, it may be necessary to keep track of additional state. This is the textbook use case for associated objects. For example, AFNetworking uses associated objects on its UIImageView category to store a request operation object, used to asynchronously fetch a remote image at a particular URL.

这篇关于异步提取已完成:仍在显示单元吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆