4
[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.

Sudheer Kolasani
  • 283
  • 5
  • 28
Vijay S
  • 185
  • 1
  • 7

2 Answers2

6

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.

haplo1384
  • 1,206
  • 1
  • 12
  • 29
  • Thanks for your response, so it means calling `refreshAllObjects ` on error can solve my problem for now. I know I have to look for actual cause but for now this will not cause any serious problem with data(Like data not saving in core data) ? – Vijay S Feb 29 '16 at 11:39
  • 2
    Ideally you would call refreshAllObjects before you start to make changes to the data you want to save. If the error you are getting is because of a conflict, and the data that changed in the persistent store conflicts with the data you are trying to modify and save, you may end up with unexpected results. If you do a refresh, then modify the data you want, then save, all of your changes will correctly save. – haplo1384 Feb 29 '16 at 16:30
0

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.

Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116