重置托管对象上下文不起作用
我在 UI 线程中有一个主托管对象上下文 (MOC),通常由工作线程更新。效果很好!
但是,我有一个视图,在 UI 线程中创建另一个 MOC(称为 EditingMOC)。我通过editingMOC中的objectID读取了myObject。然后,我在 editoringMOC 中对对象 myObject
进行了一些修改。如果用户点击 cancel
,则会发生以下情况:
[self.editingMOC reset];
myObjectEdit = [self.editingMOC existingObjectWithID:myObject.objectID error:NULL];
难道不应该将 myObjectEdit
恢复到之前的状态吗?我没有调用保存。尽管如此,myObjectEdit
仍然有我的更改。知道可能出了什么问题吗?
谢谢你!
更新:
显然 myObjectEdit
的刷新是正确的(感谢 Mark Adams)。我追踪到了这个奇怪的行为:
// RESET VALUE - OK
NSLog(@"%@", myEditObject);
self.tableView.userInteractionEnabled = NO;
// OLD VALUE AGAIN - WRONG
NSLog(@"%@", myEditObject);
我没有改变任何与userInteractionEnabled
有关的内容。此方法是否有文档中未说明的任何副作用?
I have a main managed object context (MOC) in the UI thread which is usually updated by worker threads. Works fine!
However, I have one view where I create another MOC (called editingMOC) in the UI thread. I read myObject via objectID in editingMOC. Afterwards I do some modifications on the object myObject
in the editingMOC. If the user hits cancel
, the following happens:
[self.editingMOC reset];
myObjectEdit = [self.editingMOC existingObjectWithID:myObject.objectID error:NULL];
Shouldn't that restore myObjectEdit
to it's state as it was before? I did not call save. Nevertheless myObjectEdit
has still my changes. Any idea what might be wrong?
Thank you!
Update:
Apparently the refresh of myObjectEdit
is correct (Thanks Mark Adams). I tracked it down to this weird behaivor:
// RESET VALUE - OK
NSLog(@"%@", myEditObject);
self.tableView.userInteractionEnabled = NO;
// OLD VALUE AGAIN - WRONG
NSLog(@"%@", myEditObject);
I haven't changed anything regarding to userInteractionEnabled
. Does this method have any side effects not stated in the docs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
-refreshObject:mergeChanges:
发送到您的NSManagedObjectContext
。传入您的NSManagedObject
子类并将NO
传递给mergeChanges:
。这会将对象恢复为故障,并丢弃自上次从持久存储中获取以来的任何更改。在这种情况下,该对象从未进入过存储,因此它被完全丢弃。NSManagedObjectContext 类参考 -
refreshObject:mergeChanges:
编辑:从你的问题来看,你可能在线程之间传递对象。在这种情况下,请确保通过 objectID 创建对象,而不是跨线程引用该对象。我假设你已经知道这一点了...
You need to send
-refreshObject:mergeChanges:
to yourNSManagedObjectContext
. Pass in yourNSManagedObject
subclass and passNO
tomergeChanges:
. This turns the object back into a fault and discards any changes since it was last fetched from a persistent store. In this case, the object has never been in a store, so it is completely discarded.NSManagedObjectContext Class Reference -
refreshObject:mergeChanges:
Edit: It seems from your question that you may be passing objects around between threads. In that case, be sure to create the object by objectID instead of referencing the object across threads. I'm assuming you already know this though...