【发布时间】:2016-06-07 15:30:43
【问题描述】:
在我的应用中,我下载了大量 JSON。
然后我将其存储为结构数组并使用它来填充UITableView。
结构的属性之一是图像的NSURL。另一个属性是可选的UIImage。
该结构有一个变异函数downloadImage,它使用 URL 下载图像并将其存储在其属性中。
像这样……
struct SearchItem {
// other properties...
let iconURL: NSURL
var icon: UIImage?
mutating func downloadImage() -> Task<UIImage> {
let tsc = TaskCompletionSource<UIImage>()
NSURLSession.sharedSession().downloadTaskWithURL(iconURL) {
(location, response, error) in
if let location = location,
data = NSData(contentsOfURL: location),
image = UIImage(data: data) {
self.icon = image
tsc.setResult(image)
return
}
tsc.setError(NSError(domain: "", code: 1, userInfo: nil))
}.resume()
return tsc.task
}
}
我遇到的问题是这个。 (过去我一直被这件事难住了)。
我有一个数组[SearchItem] 用于填充表格视图。
在cellForRow我有代码...if let searchItem = items[indexPath.row]...
然后它检查图像是否为 nil 并下载...
if let image = searchItem.icon {
cell.imageView.image = image
} else {
searchItem.downloadImage().continueOnSuccessWith(Executor.MainThread) {
_ in
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
}
但这永远不会将图像放入单元格中。这是因为SearchItem 是结构,所以pass-by-value。因此,我下载图像的搜索项与存储在数组中的搜索项 SearchItem 不同。
如何确保下载的图像随后存储到实际数组中的SearchItem 中?
【问题讨论】:
-
简单:使用类:D
-
@jrturton 但是...这不是结构的理想用例吗?
-
显然不行,否则它会工作
-
@jrturton 那么......如果我想在数组中存储数据时必须排除它们,那么结构到底是什么?
-
经典:你不能从包含异步任务的函数/方法中返回一些东西。你需要一个——也是异步的——完成处理程序