blwinters
blwinters

Reputation: 2191

NSPersistentContainer: merge policy of viewContext

I'm using NSPersistentContainer to create my Core Data stack. The documentation says that we should use it's viewContext property to get the main NSManagedObjectContext, but viewContext is read-only. What is the default NSMergePolicy for this context? Is it possible to change it? For example:

storeContainer.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump

Xcode doesn't complain if I set it in this way, but I'm suspicious about whether this is actually changing the policy since the context is read-only.

Edit: For reference, I learned that you can test it with:

let type = (defaultContext.mergePolicy as! NSMergePolicy).mergeType
if type == NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType {
    print("Has propertyObjectTrump type")
}

Upvotes: 4

Views: 1862

Answers (2)

Léo Natan
Léo Natan

Reputation: 57060

The context property is read-only, which means you cannot replace the context itself, however its merge policy property is not, which means you can replace the policy of the read-only context.

Upvotes: 2

Tom Harrington
Tom Harrington

Reputation: 70976

It's always possible to change the merge policy on a managed object context. It's writeable, and you can't set it at initialization time, so you set it after creation. The default is probably NSErrorMergePolicy, since that's usually the default, but you can change it to whatever you need.

Upvotes: 3

Related Questions