开发者

Editing NSManagedObject in duplicate context to merge it later on

When a user double taps a view in my application a uipopovercontroller presents him with the fields which he can edit. (Much like in the iPad calendar app)

The view represents a NSmanagedobject. To be able to cancel the operations done in the uipopovercontroller my idea was as follows:

1) create a "editManagedObjectContext" in my viewcontroller for the popover and give it the persistentstorecoordinator of my main context used throughout my app.

editContext = [[NSManagedObjectContext alloc] init];
[editContext setPersistentStoreCoordinator:[myContext persistentStoreCoordinator]];

2) fetch the object represented on the tapped view (Task*) from the new "editContext"

task = [editContext objectWithID:[taskOrNilForNewTask objectID]];

3) Use this task to do all the editing and when the user finishes he can either:

  1. Cancel the entire editing operation. This would just discard of the editContext and return.
  2. Save. This would than merge the editcontext with the original context through mergeChangesFromContextDidSaveNotification : Thus c开发者_如何学Goommiting the changes to the corresponding task in the original context.

Problem is task = [editContext objectWithID:[taskOrNilForNewTask objectID]]; results in a faulted object. And later on when I try to access the properties of a task object I get either the BAD_EXC error or my task object seems to be of some strange type ranging from: CALayer, NSCFData,...

My thought was that I might have to first save the original context, but that results in about the same errors. But since I saved just before I made the editContext I thought the save operation could be done in another thread and that could be a reason?

I just can't get my head around what I'm doing wrong and hope you guys can come up with some advice.

My approach was based on the approach in the CoreDataBook codesample from Apple (rootviewcontroller.m - (IBAction)addBook:)


Your problem was that objectWithID: returns an autoreleased object, which you were then storing in an ivar without retaining it. The system later deallocated it, and either you wound up with a garbage that gives you EXC_BAD_ACCESS or you wound up coincidentally with a different object at the same memory location. The errors you described made this clear.

The reason self.task fixes it is because the property self.task is declared retain, so assigning through the property automatically does the necessary retain. Do note that if you are not releasing it in dealloc then you will be leaking memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜