简体   繁体   English

如何在CoreData NSManagedObjectContext中还原NSUndoManager的内容?

[英]How do I restore a NSUndoManager's contents in a CoreData NSManagedObjectContext?

I'd like to use NSUndoManager in an iPhone application on CoreData (NSManagedObject) objects such that I can save (and later restore) the state of the NSUndoManager if the application exits prematurely (say, due to a phone call coming in). 我想在CoreData(NSManagedObject)对象的iPhone应用程序中使用NSUndoManager,这样,如果应用程序过早退出(例如,由于打进电话),我可以保存(然后还原)NSUndoManager的状态。 Ie as opposed to automatically discarding or saving the changes accumulated in the NSUndoManager, I would like to restore them so that the user has the option to explicitly discard or save them when they restart the app. 即与自动丢弃或保存NSUndoManager中累积的更改相反,我想还原它们,以便用户可以选择在重新启动应用程序时显式丢弃或保存它们。

Has anyone had any experience with this? 有没有人有这方面的经验? Can anyone recommend this (or an alternative) approach to managing pending changes in a NSManagedObjectContext when the application is interrupted? 当应用程序中断时,谁能推荐这种(或另一种)方法来管理NSManagedObjectContext中的挂起更改?

The NSUndoManager does not actually store state, it stores a stack of actions that will restore the state. NSUndoManager实际上并不存储状态,它存储一堆将恢复状态的操作。 For example, if you have an object XXX and it has a property name which is a string and you change that name from "Steve" to "Joe", what the NSUndoManager stores is a target, selector and object. 例如,如果您有一个对象XXX,并且它的属性名称是字符串,并且将该名称从“ Steve”更改为“ Joe”,则NSUndoManager存储的是目标,选择器和对象。 The target would be the instance of XXX, the selector would be @selector(setName:) and the object would be @"Steve" . 目标将是XXX的实例,选择器将是@selector(setName:) ,而对象将是@"Steve"

By storing that information, if the undo stack is popped it will call -setName: on the instance of object XXX with the value of @"Steve" and thus restoring its state. 通过存储该信息,如果弹出撤消堆栈,它将在对象XXX的实例上使用值@“ Steve”调用-setName: ,从而恢复其状态。 There is some additional work done around KVO, etc. but that is the basics. 关于KVO等还有一些其他工作,但这是基础。

At first I theorized that you could write out the NSManagedObjectID , the selector (using NSStringFromSelector ) and the object to disk and restore them by calling -registerUndoWithTarget: selector: object: . 最初,我认为可以将NSManagedObjectID ,选择器(使用NSStringFromSelector )和对象写到磁盘,然后通过调用-registerUndoWithTarget: selector: object:来恢复它们。 However upon further review of the documentation, there is no way to access the stack to be able to iterate over it. 但是,在进一步查阅文档时,无法访问堆栈以对其进行迭代。

Note that one possible work-around exists by using separate NSManagedObjectContexts such that some are saved on shutdown whereas others have their changes rolled back. 请注意,通过使用单独的NSManagedObjectContexts存在一种可能的解决方法,其中有些在关闭时保存,而另一些则回滚更改。 It's not perfect, but I found a suitable solution to my problem with this alternative. 这不是完美的,但是我找到了解决此问题的合适方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM