Vijay S
Vijay S

Reputation: 185

Can anyone give me some reference for this method "refreshAllObjects" in NSManagedObjectContext

[managedObjectContext refreshAllObjects]

Actually I am getting random error sometime during save context and when I call [managedObjectContext refreshAllObjects] after error, it allows me to save.
Could anyone please guide me about this method.

Upvotes: 4

Views: 2538

Answers (2)

Reinhard Männer
Reinhard Männer

Reputation: 15257

When you get an error during a context save, you may have a merge conflict between the context and the persistent store. If you update your context before the save by refreshAllObjects(), refresh(_ object:mergeChanges:) is called for every object in the context, where mergeChanges: is true. This means that attributes changed in the context are kept while attributes changed in the persistent store are updated. This is exactly what is done automatically, if you set context.mergePolicy to NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType, see the docs here and here.
But this maybe not what you want. Consider a situation where an entity with an attribute updatedAt can be changed locally and remotely, and the requirement is that individual attributes may not be mixed, but only the complete entity that has been updated last should be kept. In this case, none of the predefined merge policies apply, and one has to set up a custom merge policy that checks the updatedAt attribute. How this can be done is described here.

Upvotes: 0

haplo1384
haplo1384

Reputation: 1236

Calling refreshAllObjects calls refreshObject:mergeChanges on all objects in the context. You can see the documentation on refreshObject:mergeChanges here:

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/#//apple_ref/occ/instm/NSManagedObjectContext/refreshObject:mergeChanges:

It is possible that your persistent store has been modified by some other context, so you get an error when you try to save to it from your current context. If you refresh your current context first, then any modified data will be merged, and you can now save without conflicts.

Upvotes: 6

Related Questions