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

时间:2015-08-18 05:37:21

标签: cocoa core-data nsmanagedobjectcontext

我正在通过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,但我并不是很理解。

2 个答案:

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