Search code examples
ioscore-datansmanagedobjectcontext

ios core data roll back


I use the roll back method of the managed object context to discard changes made but I encountered a problem: If I have different view controllers, and each of them can made changes to different database data, and if the first controller perform roll back method, I do not want it to roll back changes made by the second controller. Is it anyway to just roll back a specific entity, but not all? or am I supposed to used mutiple managed object contexts?


Solution

  • You cannot roll back only a partial change set of an NSManagedObjectContext. The best way to do what you're talking about is to make a new NSManagedObjectContext that is a child of a parent context. When you save it, the changes get pushed to the parent (you have to make sure that you save your parent contexts to actually persist to disk). Additionally, if you isolate change sets in this manner, you don't even have to call rollback on the child contexts, you can just throw them away.

    Note that to use the parent/child relationships of the NSManagedObjectContext you must the initWithConcurrencyType: method to initialize all your contexts, and you must specify either NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType. It is important to note that this has implications on how you access the context. If you are not on the main queue using a context with a concurrency type of NSMainQueueConcurrencyType, you will have to put all method calls that interact with the context inside a block and pass it to the contexts performBlock: or performBlockAndWait: method.

    The documentation is rather thin on this topic. The only reference I can find outside of WWDC videos is in this iOS 5 release notes document.