Search code examples
iosmultithreadingcore-datansmanagedobjectcontext

How to rollback changes on temporary context?


I create a temporaryContext like this:

let temporaryContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
temporaryContext.parentContext = Utility.managedObjectContext()
temporaryContext.performBlockAndWait({

    // .. here I have done some changes on temporaryContext

    let success = temporaryContext.save(nil)

    //GUI get updated, GUI use MAIN context 
})

I want to roll back changes, so I do this:

temporaryContext.performBlockAndWait({                                
    temporaryContext.rollback()
    let success = temporaryContext.save(nil)

    //GUI not get restored to the default variable
})

But it has no effect, parent context will not rolled back, why?


Solution

  • When you call rollback it only reverts unsaved changes in that context. In the first block of code you have already saved those changes and thus rollback will not do anything.

    When you called save in the first code block all of the changes were committed to the parent context which, I assume, is the main context in this case. Because you have not yet called save on the main context you should still be able to call rollback on the main context to remove those changes in the main context.