【发布时间】:2018-03-23 01:52:34
【问题描述】:
我正在构建一个应用程序,它使用 Core Data 数据库将其数据存储在产品上。这些产品显示在UICollectionView 中。此集合视图中的每个单元格都显示其包含的产品的基本信息,包括一张图片。
虽然单元格相对较小,但它们显示的原始图像最好相当大,因为它们也应该能够在更大的图像视图中显示。图片是直接从我的CellForItemAtIndexPath:方法中的Core Data加载的:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionWineCell
var current: Product!
//product details are set on labels
//image is set
if current.value(forKey: "image") != nil {
let image = current.value(forKey: "image") as! WineImage
let loadedImage = UIImage(data: image.image)
cell.imageview.image = loadedImage
} else {
cell.imageview.image = UIImage(named: "ProductPlaceholder.png")
}
return cell
}
当产品集合增加时,滚动会变得更加颠簸,并且会丢失很多帧。这对我来说很有意义,但到目前为止我还没有找到合适的解决方案。在线查看时,有很多文档和框架可用于从 URL(在线或文件路径)异步加载图像,但从 Core Data 执行此操作似乎并不常见。
我已经尝试过使用异步获取请求:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"ProductImage")
fetchRequest.predicate = NSPredicate(format: "product = %@", current)
let asyncRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { results in
if let results = results.finalResult {
let result = results[0] as! ProductImage
let loadedImage = UIImage(data: result.image)
DispatchQueue.main.async(execute: {
cell.wineImage.image = loadedImage
})
}
}
_ = try! managedObjectContext.executeRequest(asyncRequest)
但是,这种方法似乎也不能解决问题
问题
在显示来自 Core Data 的大量数据(包括图像)时,如何以不会导致 UICollectionView 中的滞后和丢帧的方式加载图像?
【问题讨论】:
标签: ios iphone asynchronous core-data uicollectionview