【发布时间】:2021-06-17 16:13:13
【问题描述】:
假设我想在 CoreData 的Playlist 实体中添加一个新项目并将其放入后台线程并将其推回主线程,然后将其反映在 tableView 上。好吧,该代码在没有后台线程实现的情况下运行良好。
但是当我应用下面的后台代码时,在执行createPlaylist 之后,tableView 变成了空白空间(没有任何项目出现),尽管print(self?.playlists.count) 给出了正确的行数。
在处理 GCD 时,我将一些繁重的代码放在后台队列中,并在同一个闭包中推回主队列以进行 UI 更新。但这似乎在这里不起作用,我google了一段时间,但仍然无法解决问题。
import UIKit
import CoreData
class PlayListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var songs = [Song]()
var position = 0
let container = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
private var playlists = [Playlist]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 1, alpha: 1)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "playlistCell")
configureLayout()
getAllPlaylists()
}
// MARK: Core data functions
func getAllPlaylists() {
do {
let context = self.container.viewContext
playlists = try context.fetch(Playlist.fetchRequest())
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
print("count: \(playlists.count)")
// printThreadStats()
} catch {
print("getAllPlaylists failed, \(error)")
}
}
func createPlaylist(name: String) {
container.performBackgroundTask { context in
let newPlaylist = Playlist(context: context)
newPlaylist.name = name
do {
try context.save()
self.playlists = try context.fetch(Playlist.fetchRequest())
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
print(self?.playlists.count)
}
} catch {
print("Create playlist failed, \(error)")
}
}
}
// MARK: tableView data source implementation
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playlists.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let playlist = playlists[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "playlistCell", for: indexPath)
cell.textLabel?.text = playlist.name
// cell.detailTextLabel?.text = "2 songs"
return cell
}
自动生成的 fetchRequest 和属性定义
import Foundation
import CoreData
extension Playlist {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Playlist> {
return NSFetchRequest<Playlist>(entityName: "Playlist")
}
@NSManaged public var name: String?
}
【问题讨论】:
标签: swift multithreading core-data