NSNotification.Name.NSManagedObjectContextDidSave
需要在与调用它的线程相同的线程上被调用。
现在,我变得不合理地感到困惑。是否需要在主线程上调用managedContext.save()
?如果不需要,如何保证在调用.save
时正在使用哪个线程?
我感到困惑的部分原因是,我正在URLSession
请求的中间进行此操作。这是我的检索结果:
func retrieveDataFromURLIfNeeded() {
let fetchRequest = NSFetchRequest<Commit>(entityName: "Commit")
let count = try! coreDataStack.managedContext.count(for: fetchRequest)
print ("count", count)
guard count == 0 else { return }
let gitUrl = URL(string: "https://api.github.com/repos/apple/swift/commits?per_page=100")
// request happens on the background thread
URLSession.shared.dataTask(with: gitUrl!) { (data, response, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
// Assign the NSManagedObject Context to the decoder
decoder.userInfo[CodingUserInfoKey.context!] = self.coreDataStack.managedContext
let _ = try decoder.decode([Commit].self, from: data)
// DispatchQueue.main.async { [weak self] in
// guard let self = self else {return}
print ("saving")
self.coreDataStack.saveContext()
// }
} catch let err {
print("Err", err)
}
}.resume()
}
因此,无需明确定义
在上面代码中的主线程上是self.coreDataStack.saveContext()
managedContext.save()
是否需要位于主线程上?