Search code examples
swiftswift2ios9xcode7

ManagedObjectContext Syntax


So, it tells me:

init() was deprecated in IOS 9.0: Use -initWithConcurrencyType: instead

var managedObjectContext = NSManagedObjectContext()

That's my code. It gave the error too, so how should I change it?


Solution

  • Since iOS 9 NSManagedObjectContext() is deprecated and is recommended to create an NSManagedObjectContext with, as hinted, -initWithConcurrencyType: instead.

    Usage when creating a NSManagedObjectContext in iOS 9:

    let managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    

    With -initWithConcurrencyType:, we need to specify a concurrency type.

    The above example creates one with a .MainQueueConcurrencyType, which is one of the three one can specify:

    case ConfinementConcurrencyType
    

    Specifies that the context will use the thread confinement pattern.

    case PrivateQueueConcurrencyType
    

    Specifies that the context will be associated with a private dispatch queue.

    case MainQueueConcurrencyType
    

    Specifies that the context will be associated with the main queue.

    With the deprecated NSManagedObjectContext(), if my memory serves, the default was of type .ConfinementConcurrencyQueue.

    To stay on the topic, if you are dealing with UI elements (i.e., updating a textLabel thereby), use the .MainQueueConcurrencyQueue.