开发者

Why this code fails to empty undo stack

- (void)cancel {
//   [managedObjectContext.undoManager disableUndoRegistration];
     [managedObjectContext deleteObject:object]; // I don't want this deletion to be recorded on the undo stack which is empty at this point.
//   [managedObjectContext.undoManager enableUndoRegistration];
     [managedObjectContext.undoManager removeAllActions];
}

With this code, I still got the deletion on the undo stack, even uncommenting those two lines can not p开发者_如何学Crevent the recording. Why?


You'll need to call -processPendingChanges on the managed object context before disabling and before re-enabling undo processing. Core Data delays registering undo events until processPendingChanges to allow for coalescing multiple changes to the same attribute and similar shortcuts.


What is calling -cancel? I have encountered situations where some other method is registering an undo event (and core data may be "helpfully" doing this for you). You may find that your undo stack is empty at the end of -cancel but gets an event added by the calling method.

In these cases choosing "Undo" doesn't actually (un)do anything, the event has nothing to undo. To prevent these superfluous events you need to disable undo registration (and then reenable it) in the calling method. Something along the lines of...

- (void)doSomething {
    // Disable undo until we definitely want to undo stuff
    [managedObjectContext.undoManager disableUndoRegistration];

    // Stuff goes here

    if ( userCancelled ) {
        [self cancel];
        [managedObjectContext.undoManager enableUndoRegistration];
        return;
    }

    // We actually want user to be able to undo the following stuff
    [managedObjectContext.undoManager enableUndoRegistration];

    // More stuff goes here
}

Before delving too far into this do some simple NSLog checks to see what is on the undo stack when (and to make sure you are sending messages to a real live NSUndoManager rather than a nil object).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜