我正在通过Core Data Stack in Swift - Demystified,但当我到达
行时self.context = NSManagedObjectContext()
我收到了警告
`init()` was deprecated in iOS 9.0: Use -initWithConcurrencyType: instead
我发现我可以为self.context =
NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.ConfinementConcurrencyType)
NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
但由于ConfinementConcurrencyType
现已弃用MainQueueConcurrencyType
和PrivateQueueConcurrencyType
。这两者有什么区别,我应该如何选择使用哪一个?我读过this documentation,但我并不是很理解。
答案 0 :(得分:27)
您基本上将始终拥有NSMainQueueConcurrencyType
的至少1个上下文和NSPrivateQueueConcurrencyType
的许多上下文。 NSPrivateQueueConcurrencyType
通常用于在后台保存或获取核心数据(如果尝试使用Web服务同步记录)。
NSMainQueueConcurrencyType
创建与主队列关联的上下文,非常适合与NSFetchedResultsController
一起使用。
默认核心数据堆栈使用NSMainQueueConcurrencyType
的单个上下文,但您可以通过利用多个NSPrivateQueueConcurrencyType
来执行任何不影响UI的工作,从而创建更好的应用。
答案 1 :(得分:7)
将以下两项功能替换为:
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}