问题:我正在使用通过Apple API(所有本地)访问的音乐中的艺术资源来创建4个图像拼贴作为表格视图中播放列表的单元格中的图像。我已经尝试了一些方法,我会将性能提升到可接受的水平,但总会有某种打嗝。
方法1)执行处理代码以返回每个单元格的拼贴图像。这对我设备上的少数播放列表来说总是很好,但是我收到了来自重度用户的报告,说他们无法滚动。
方法2)在viewdidload()中,遍历所有播放列表并将拼贴图像和其中一个UUID保存在可变数组中,然后使用UUID获取单元格的图像。这似乎可以正常加载视图延迟 - 但由于某些原因后续加载需要更长的时间。
所以在我尝试对方法2进行更多的故障排除之前,我想知道我是否正在以完全错误的方式直接解决这个问题?我已经查看了GCD和NSCache,就GCD而言,我不知道如何制作一个合适的设计模式来利用它,如果它甚至可能,因为UI更新和存储访问等内容可能是什么挡路。
import UIKit
import MediaPlayer
class playlists: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate {
...
var compositedCellImages:[(UIImage, UInt64)] = []
...
override func viewDidLoad() {
super.viewDidLoad()
let cloudFilter:MPMediaPropertyPredicate = MPMediaPropertyPredicate(value: false, forProperty: MPMediaItemPropertyIsCloudItem, comparisonType: MPMediaPredicateComparison.equalTo)
playlistsQuery.addFilterPredicate(cloudFilter)
playlistQueryCollections = playlistsQuery.collections?.filter{$0.value(forProperty: MPMediaPlaylistPropertyName) as? String != "Purchased"} as NSArray?
var tmpArray:[MPMediaPlaylist] = []
playlists = playlistQueryCollections as! [MPMediaPlaylist]
for playlist in playlists {
if playlist.value(forProperty: "parentPersistentID") as! NSNumber! == playlistFolderID {
tmpArray.append(playlist)
compositedCellImages.append(playlistListImage(inputPlaylistID: playlist.persistentID))
}
}
playlists = tmpArray
...
}
// MARK: - Table view data source
...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "playlistCell", for: indexPath) as! playlistCell
...
let currentItem = playlists[indexPath.row]
...
cell.playlistCellImage.image = compositedCellImages[indexPath.row].0
}
}
return cell
}
...
func playlistListImage(inputPlaylistID:MPMediaEntityPersistentID) -> (UIImage,UInt64) {
var playlistData:[MPMediaItem] = []
var pickedArtwork:[UIImage] = []
var shuffledIndexes:[Int] = []
let playlistDetailImage:collageImageView = collageImageView()
playlistDetailImage.frame = CGRect(x: 0, y: 0, width: 128, height: 128)
let playlistDataPredicate = MPMediaPropertyPredicate(value: NSNumber(value: inputPlaylistID as UInt64), forProperty: MPMediaPlaylistPropertyPersistentID, comparisonType:MPMediaPredicateComparison.equalTo)
let playlistDataQuery = MPMediaQuery.playlists()
let cloudFilter:MPMediaPropertyPredicate = MPMediaPropertyPredicate(value: false, forProperty: MPMediaItemPropertyIsCloudItem, comparisonType: MPMediaPredicateComparison.equalTo)
playlistDataQuery.addFilterPredicate(cloudFilter)
playlistDataQuery.addFilterPredicate(playlistDataPredicate)
playlistData = playlistDataQuery.items!
playlistData = playlistData.filter{$0.mediaType == MPMediaType.music}
for (index,_) in playlistData.enumerated() {
shuffledIndexes.append(index)
}
shuffledIndexes.shuffleInPlace()
for (_,element) in shuffledIndexes.enumerated() {
if playlistData[element].artwork != nil {
pickedArtwork.append(playlistData[element].artwork!.image(at: CGSize(width: 64, height: 64))!)
}
if pickedArtwork.count == 4 { break }
}
while pickedArtwork.count < 4 {
if pickedArtwork.count == 0 {
pickedArtwork.append(UIImage(named: "missing")!)
} else {
pickedArtwork.shuffleInPlace()
pickedArtwork.append(pickedArtwork[0])
}
}
pickedArtwork.shuffleInPlace()
playlistDetailImage.drawInContext(pickedArtwork, matrixSize: 2)
return ((playlistDetailImage.image)!,inputPlaylistID)
}
...
}
...
class collageImageView: UIImageView {
var inputImages:[UIImage] = []
var rows:Int = 1
var cols:Int = 1
func drawInContext(_ imageSet: [UIImage], matrixSize: Int) {
let frameLeg:Int = Int(self.frame.width/CGFloat(matrixSize))
var increment:Int = 0
UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
self.image?.draw(in: self.frame)
for col in 1...matrixSize {
for row in 1...matrixSize {
imageSet[increment].draw(in: CGRect(x: (row - 1) * frameLeg, y: (col-1) * frameLeg, width: frameLeg, height: frameLeg))
increment += 1
}
}
self.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
答案 0 :(得分:1)
一种方法是修改原始方法1,但添加延迟加载和缓存。
有关如何进行延迟加载的示例,请参阅https://developer.apple.com/library/content/samplecode/LazyTableImages/Introduction/Intro.html
基本思想是,您只在滚动完成时尝试计算图像(在上面的示例中,他们从URL加载图像,但您可以用计算替换它)。
此外,您可以缓存每行的计算结果,以便在用户来回滚动时,您可以先检查缓存的值。同时清除didReceiveMemoryWarning中的缓存。
所以在tableView(_:UITableView,cellForRowAt:IndexPath)
中if <cache contains image for row> {
cell.playlistCellImage.image = <cached image>
} else if tableView.isDragging && !tableView.isDecelerating {
let image = <calculate image for row>
<add image to cache>
cell.playlistCellImage.image = image
} else {
cell.playlistCellImage.image = <placeholder image>
}
然后覆盖滚动视图的委托方法
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
loadImagesForOnScreenRows()
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
loadImagesForOnScreenRows()
}
并实现loadImagesForOnScreenRows()
for path in tableView.indexPathsForVisibleRows {
let image = <calculate image for row>
<add image to cache>
if let cell = tableView.cellForRow(at: path) {
cell.playlistCellImage.image = image
}
}
最后一个优化是将实际计算推送到后台线程,但你应该发现上面的延迟加载可能就足够了。
更新 - 在后台线程上计算。
一般的想法是在后台队列上使用DispatchQueue运行计算,然后在结果准备好后,更新UI线程上的显示。
类似以下(未经测试的)代码
func loadImageInBackground(inputPlaylistID:MPMediaEntityPersistentID, completion:@escaping (UIImage, UInt64))
{
let backgroundQueue = DispatchQueue.global(dos: DispatchQoS.QoSClass.background)
backgroundQueue.async {
let (image,n) = playlistListImage(inputPlaylistID:inputPlaylistID)
DispatchQueue.main.async {
completion(image,n)
}
}
}
在tableView(_:UITableView,cellForRowAt:IndexPath)中,而不是直接计算图像,请调用背景方法:
if <cache contains image for row> {
cell.playlistCellImage.image = <cached image>
} else if tableView.isDragging && !tableView.isDecelerating {
cell.playlistCellImage.image = <placeholder image>
loadImageInBackground(...) {
(image, n) in
if let cell = tableView.cellForRow(at:indexPath) {
cell.playlistCellImage.image = image
}
<add image to cache>
}
} else {
cell.playlistCellImage.image = <placeholder image>
}
和loadImagesForOnScreenRows()中的类似更新。
注意在回调处理程序中再次检索单元格的额外代码。由于此更新可以异步进行,因此原始单元很可能已被重用,因此您需要确保更新正确的单元