gpt4 book ai didi

ios - 从 NSData 到 UIImage 的转换非常慢,阻止 UITableView

转载 作者:行者123 更新时间:2023-11-28 06:11:34 24 4
gpt4 key购买 nike

我从 Core Data 获得了 NSData,当我从 NSData 转换为 UIImage 时,它使我的 UITableView 滚动非常慢。在将图像存储到 Core Data 之前,我已经调整了图像的大小。有没有好的方法来做到这一点。一开始想用Kingfisher,但是好像没有这种方法可以实现。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ListTableViewCell"

guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ListTableViewCell else {
fatalError("The dequeued cell is not an instance of MealTableViewCell.")
}
//cell.imageContentPhoto.kf.setImage(with: url)
cell.imageContentPhoto.image = UIImage(data: photos[indexPath.row] as Data)//photo is NSData, I got it from Core Data

return cell
}

最佳答案

您的问题不是转换速度慢,而是滚动时转换了很多次。

为了优化 UITable,iOS 不会为 n 行创建 n 个单元格。它创建 x+2 个单元格 (IIRC),其中 x 是可见单元格的数量。

当调用 cellForRowAt 时,您调用 dequeueReusableCell,它获取一个空闲单元格并将其分配给该行。这样,当您滚动时,不会发生对象的初始化,并且会减慢向下滚动的速度。

您的代码的问题(现在很明显)是,在将单元格分配给行之后,您再次转换图像并对其进行初始化。

你应该做的是提前初始化图像数组,例如在 viewDidLoad 中。那么您的代码将如下所示:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ListTableViewCell"

guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ListTableViewCell else {
fatalError("The dequeued cell is not an instance of MealTableViewCell.")
}
//cell.imageContentPhoto.kf.setImage(with: url)
cell.imageContentPhoto.image = imagesArray[indexPath.row] // or something similar

return cell
}

当然,如果您有很多不同的图像,则可能值得进行某种延迟加载。滚动时保留占位符图像,当滚动停止时,仅加载相关图像。这当然要复杂得多,留给学生作为练习。

关于ios - 从 NSData 到 UIImage 的转换非常慢,阻止 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46374746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com