NSManagedObjectContext():`init()` 在 iOS 9.0 中被弃用:使用 -initWithConcurrencyType

NSManagedObjectContext(): `init()` was deprecated in iOS 9.0: Use -initWithConcurrencyType

我正在完成 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 现在也已弃用,所以我只剩下 MainQueueConcurrencyTypePrivateQueueConcurrencyType。这两者有什么区别,我应该如何选择使用哪一个?我看了this documentation,但没看懂

基本上,您将始终至少有 1 个上下文 NSMainQueueConcurrencyType 和许多上下文 NSPrivateQueueConcurrencyTypeNSPrivateQueueConcurrencyType 通常用于在后台将内容保存或提取到核心数据(例如尝试将记录与 Web 服务同步)。

NSMainQueueConcurrencyType 创建与主队列关联的上下文,非常适合与 NSFetchedResultsController 一起使用。

默认核心数据堆栈使用 NSMainQueueConcurrencyType 的单个上下文,但您可以通过利用多个 NSPrivateQueueConcurrencyType 来完成任何不影响 UI 的工作,从而创建更好的应用程序].

将这两个函数替换为以下函数:

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()
        }
    }
}