如何回滚临时上下文的更改?
How to rollback changes on temporary context?
我创建了一个这样的临时上下文:
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
})
我想回滚更改,所以我这样做:
temporaryContext.performBlockAndWait({
temporaryContext.rollback()
let success = temporaryContext.save(nil)
//GUI not get restored to the default variable
})
但是没有效果,父上下文不会回滚,为什么?
当您调用 rollback
时,它只会还原该上下文中未保存的更改。在第一段代码中,您已经保存了这些更改,因此 rollback
不会执行任何操作。
当您在第一个代码块中调用 save
时,所有更改都提交给父上下文,我认为在这种情况下它是主要上下文。因为您还没有在主上下文中调用 save
,您应该仍然能够在主上下文中调用 rollback
以删除主上下文中的那些更改。
我创建了一个这样的临时上下文:
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
})
我想回滚更改,所以我这样做:
temporaryContext.performBlockAndWait({
temporaryContext.rollback()
let success = temporaryContext.save(nil)
//GUI not get restored to the default variable
})
但是没有效果,父上下文不会回滚,为什么?
当您调用 rollback
时,它只会还原该上下文中未保存的更改。在第一段代码中,您已经保存了这些更改,因此 rollback
不会执行任何操作。
当您在第一个代码块中调用 save
时,所有更改都提交给父上下文,我认为在这种情况下它是主要上下文。因为您还没有在主上下文中调用 save
,您应该仍然能够在主上下文中调用 rollback
以删除主上下文中的那些更改。