CoreData:清除NSManagedObjectContext的更改 [英] CoreData: Clear changes from NSManagedObjectContext
问题描述
我在应用程序委托级别实例化一个 NSManagedObjectContext
对象,并在所有 UIViewController
中共享它。下面是我在一个视图控制器中使用的代码:
I'm instantiating a NSManagedObjectContext
object at the Application delegate level and sharing it across all my UIViewController
s. Here's the code that I use to access it in one of my View Controllers:
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
modelObj = (Model *) [NSEntityDescription insertNewObjectForEntityForName:@"Model" inManagedObjectContext:[appDelegate managedObjectContext]];
现在在此屏幕中,我有一个 UITableView
9行&每个单元都有一个 UITextField
。当用户向文本字段中输入值时,我将它们分配到 modelObj
中。现在,我的用户可以选择取消并放弃所有更改或将其保存到磁盘。我有保存代码工作正常。但是在用户尝试丢弃更改的情况下,我不知道该怎么办。似乎没有一个 [managedObjectContext discardChanges]
方法将它们全部丢弃。
Now in this screen, I have a UITableView
with 9 rows & each cell has a UITextField
. As the user inputs values into the textfields, I assign them into modelObj
. Now, my user has an option to cancel out and discard all the changes or save them to disk. I have the save code working fine. But in the case when a user tries to discard the changes, I'm not sure what to do. There doesn't seem to be a [managedObjectContext discardChanges]
method to throw them all away.
- 创建
NSManagedObjectContext的新实例
为每个控制器,而不是在应用程序之间共享。 - 或者,我可以在我的代码中创建一堆
NSString
s,并在其中保存用户值,然后调用
- Create a new instance of
NSManagedObjectContext
for each controller instead of sharing one across the application. - Or, I could create a bunch of
NSString
s in my code and save user values in them and callinsertNewObjectForEntityForName:
only if the user clicks save.
哪一种方式是正确的?或者有一种方法让 NSManagedObjectConext
舍弃所有对它做的更改吗?
Which way is the right one? Or is there a way to make NSManagedObjectConext
discard all the changes that were made to it?
>
Teja。
Thanks,
Teja.
推荐答案
NSManagedObjectContext有一个简单的方法:
NSManagedObjectContext has a simple method for this:
[managedObjectContext rollback];
此方法从撤消堆栈中删除所有内容,舍弃所有插入和删除,他们最后的承诺值。 (文档)
This method "removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values." (documentation)
除非我缺少某些东西,否则应该给你所需要的一切。
Unless I'm missing something, that should give you everything you need.
这篇关于CoreData:清除NSManagedObjectContext的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!