我有一个表视图,其中包含音乐库中所有歌曲的列表。一开始,我获取所有歌曲,并将它们的信息保存到如下数组中:
var songs = [Song]()
private func loadSongs(){
let itunesSongs = MPMediaQuery.songs().items
if itunesSongs == nil {
return;
}
for song in itunesSongs!{
let artist = song.albumArtist
let trackTitle = song.title
let image = song.artwork?.image(at: CGSize(width: 90, height: 90))
let url = song.assetURL?.absoluteString ?? ""
let song1 = Song(title: trackTitle ?? "", artist: artist ?? "", image: image, url: url)
songs.append(song1)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "SongTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SongCell else {
fatalError("The dequeued cell is not an instance of SongCell.")
}
let song = playerManager.songs[indexPath.row]
cell.setAttributes(song: song)
cell.preservesSuperviewLayoutMargins = false
return cell
}当我在一个有超过10000首歌曲的设备上测试这个程序时,启动该应用程序花费了5-10秒时间。因此我修改了填充表视图的方式,如下所示:
var itunesSongs: MPMediaQuery.songs().items
func getSong(index: Int) -> Song {
if(index >= songs.count){
let song = itunesSongs![index]
let ans = Song(title: song.title ?? "", artist: song.albumArtist ?? "", image: song.artwork?.image(at: CGSize(width: 90, height: 90)), url: song.assetURL?.absoluteString ?? "")
songs.append(ans)
}
return songs[index]
}因此,我将在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)中使用tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath),而不是使用songs数组。
问题解决了,应用程序正常启动。然而,偶尔,我会在return songs[index]线路上看到return songs[index]。当我快速滚动时会发生这种情况,每次都使用不同的索引。我试着一次取一首100首而不是一首,但这也解决不了这个问题。
我正在考虑使用后台线程来填充songs数组,但不确定这是否是正确的方法。
发布于 2018-03-05 20:08:22
问题是表视图没有按顺序调用getSong()。例如,表视图可以调用getSong(6)然后调用getSong(3)。我更新了该职能如下:
func getSong(index: Int) -> Song {
while (index >= songs.count){
let song = itunesSongs![songs.count]
let ans = Song(title: song.title ?? "", artist: song.albumArtist ?? "", image: song.artwork?.image(at: CGSize(width: 90, height: 90)), url: song.assetURL?.absoluteString ?? "")
songs.append(ans)
}
return songs[index]
}发布于 2018-03-07 05:52:50
一种可能的解决方案
不要使用歌曲数组。也许在歌曲数组中添加大量的条目(10000)需要时间。相反,
在viewdidLoad()中获得这样的歌曲
let itunesSongs = MPMediaQuery.songs().items
在cellforRowAt中,从itunesSongs (标题、艺术家等)获取歌曲数据,填充您的单元格并返回。像这样的事情
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "SongTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SongCell else {
fatalError("The dequeued cell is not an instance of SongCell.")
}
let song = itunesSongs[indexPath.row]
cell.setAttributes(song: song)
cell.preservesSuperviewLayoutMargins = false
return cell
}https://stackoverflow.com/questions/49118205
复制相似问题