在创建从 CoreData 获取数据的简单代码后,我意识到触发了一些未知错误。我读到在后台获取数据并不是那么简单。不幸的是,我是 iOS 开发的新手,只知道 Swift,那里有很多 Objective-C 教程。 这是我的代码:
func reloadData() {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Person")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
let people = results as! [NSManagedObject]
for person in people {
collectionViewData.append(person)
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
dispatch_async(dispatch_get_main_queue()) {
self.collectionView?.reloadData()
}
}
}
如何在 Swift 中使用 NSPrivateQueueConcurrencyType 和类似的东西来实现它?
最佳答案
您的代码几乎肯定会失败。您正在从后台线程访问主托管对象上下文。
从您的代码看来,您似乎不需要后台获取。删除代码的所有 GCD(grand central dispatch)部分,你应该没问题。
作为引用,这是您在 Core Data 中执行后台操作的方式:
let moc = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
moc.parentContext = <insert main context here>
moc.performBlock {
// make changes, fetch, save
}
保存后,您的主要上下文将发生变化。要更新 TableView ,请实现 NSFetchedResultsController
及其委托(delegate)方法以自动执行此操作。
关于ios - 如何在后台使用核心数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34961104/