Я создаю addManagedObjectContext как область блокнота для новых сущностей, а затем объединяю новую сущность с моим основным ManagedObjectContext в «Сохранить», подобно тому, как это показано в примере CoreDataBooks.
После объединения вашей новой сущности, как получить краткую ссылку на нее для использования при отображении подробного представления?
Вам нужно заставить контроллер результатов выборки выйти и снова выполнить выборку (дорого, как отмечено в коде CoreDataBooks)? Я предполагаю, что начальный идентификатор объекта в 'добавленииManagedObjectContext' не останется прежним после слияния.
В проекте Recipes такой проблемы нет, потому что вы создаете и работаете с новым объектом в одном ManagedObjectContext. Поэтому у вас есть ссылка на вновь созданный элемент, чтобы показать его подробный вид.
Из CoreDataBooks:
/**
Add controller's delegate method; informs the delegate that the add operation has completed, and indicates
whether the user saved the new book.
*/
- (void)addViewController:(AddViewController *)controller didFinishWithSave:(BOOL)save {
if (save) {
/*
The new book is associated with the add controller's managed object context.
This is good because it means that any edits that are made don't affect the
application's main managed object context -- it's a way of keeping disjoint edits
in a separate scratchpad -- but it does make it more difficult to get the new book
registered with the fetched results controller.
First, you have to save the new book. This means it will be added to the persistent
store. Then you can retrieve a corresponding managed object into the application
delegate's context. Normally you might do this using a fetch or using objectWithID: -- for example
NSManagedObjectID *newBookID = [controller.book objectID];
NSManagedObject *newBook = [applicationContext objectWithID:newBookID];
These techniques, though, won't update the fetch results controller, which
only observes change notifications in its context.
You don't want to tell the fetch result controller to perform its fetch again
because this is an expensive operation.
You can, though, update the main context using mergeChangesFromContextDidSaveNotification: which
will emit change notifications that the fetch results controller will observe.
To do this:
1 Register as an observer of the add controller's change notifications
2 Perform the save
3 In the notification method (addControllerContextDidSave:), merge the changes
4 Unregister as an observer
*/
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self selector:@selector(addControllerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:addingManagedObjectContext];
NSError *error;
if (![addingManagedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
[dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:addingManagedObjectContext];
}
// Release the adding managed object context.
self.addingManagedObjectContext = nil;
// Dismiss the modal view to return to the main list
[self dismissModalViewControllerAnimated:YES];
}
/**
Notification from the add controller's context's save operation. This is used to update the
fetched results controller's managed object context with the new book instead of performing
a fetch (which would be a much more computationally expensive operation).
*/
- (void)addControllerContextDidSave:(NSNotification*)saveNotification {
NSLog(@"addControllerContextDidSave");
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
// Merging changes causes the fetched results controller to update its results
[context mergeChangesFromContextDidSaveNotification:saveNotification];
}