Undo manager not up to date with NSPersistentDocument
I have some calculated values in the core data database that I need to update just before saving. Basically I'm numbering some entities in order to ease up the navigation between them.
Currently I'm observing NSManagedObjectContextWillSaveNotification
and trying to do this numbering there. It would seem that the changes that I make are saved but undo manager still seems to have some modifications. This makes the document look like it has changes (mark on the close button) even though managed object context says that it doesn't have (hasChanges
). If I undo once, the document looks like it has no changes but in turn, the managed object context does.
Does the undo manager somehow reset itself in the wrong place or am I doing something wrong?
开发者_如何学GoUpdate
The somewhat obfuscated code in which I'm doing this renumbering looks like this:
- (void)managedObjectContextWillSave:(NSNotification *)notification
{
// Force the content view controller to save any pending changes.
[_contentViewController saveChanges];
NSArray *itemSortDesc = [self sortDescriptorsForSomeItem];
NSArray *items = [SomeItem findAllObjectsInContext:self.managedObjectContext
andSortBy:itemSortDesc];
NSUInteger i = 0;
for (SomeItem *i in items)
{
i.uid = [NSNumber numberWithUnsignedInteger:i++];
}
}
The _contentViewController
contains a text field that will be parsed in to multiple instances of SomeItem
.
I'm guessing that your numbering affects the undo stack.
I would probably try to handle this in NSManagedObject willSave
instead of using NSManagedObjectContextWillSaveNotification
but I suspect that won't solve your problem.
You could try this:
[[self.managedObjectContext undoManager] disableUndoRegistration];
// do the renumbering
[self.managedObjectContext processPendingChanges];
[[self.managedObjectContext undoManager] enableUndoRegistration];
I use this to avoid dirtying a brand new document during initialization. I'm not certain it will work correctly for saving, but it might be worth trying.
精彩评论