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

Sur*_*gch 25 cocoa core-data nsmanagedobjectcontext

我正在使用Swift中的Core Data Stack - Demystified,但是当我到达线路时

self.context = NSManagedObjectContext()
Run Code Online (Sandbox Code Playgroud)

我收到了警告

`init()` was deprecated in iOS 9.0: Use -initWithConcurrencyType: instead
Run Code Online (Sandbox Code Playgroud)

我看到我可以做以下其中一项了 self.context =

NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.ConfinementConcurrencyType)
NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
Run Code Online (Sandbox Code Playgroud)

但是ConfinementConcurrencyType现在也被弃用了,这让我MainQueueConcurrencyTypePrivateQueueConcurrencyType.这两者有什么区别,我应该如何选择使用哪一个?我阅读了这份文档,但我并不理解.

DBo*_*yer 27

你基本上总是至少有1个上下文NSMainQueueConcurrencyType和许多上下文NSPrivateQueueConcurrencyType.NSPrivateQueueConcurrencyType通常用于在后台保存或获取核心数据(如果尝试使用Web服务同步记录).

NSMainQueueConcurrencyType创建一个与主队列这是完美的与使用相关的情境NSFetchedResultsController.

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


小智 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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)