问题
I have several WebViews that I swap in and out of my view hierarchy. Some of these WebViews contain form fields, so I implement the editingDelegate to provide the NSUndoManager for my document.
The problem is that any typing done in the WebView generates actions that are placed on the undo stack. After the view is removed from the hierarchy, the actions are still in the undo stack. At that point, if a user uses Cmd-Z to "Undo Typing", an exception is thrown because -undoEditing: is being sent to a deallocated instance of WebEditorUndoTarget. (A private class used in the WebKit implementation.)
I can't use -removeAllActionsWithTarget: because I can't reference the target. It appears the only solution is to disable undo registration for the WebView.
Am I missing something or is this a limitation of a WebView?
回答1:
One private API solution is to invoke -[WebView _clearUndoRedoOperations]. Haven't found a public API solution yet.
回答2:
In my opinion the WebView should take responsibility for removing itself or any subservient objects from the WebView's undoManager: in this case, yours.
Judging from your description, it's not doing this. I suspect that your aim to find the target so you can remove it explicitly will be fruitless, so I'd like to suggest another solution, which I've either used before, or I got far enough down this road to think about using ;)
The thought I had for this kind of situation is to use a custom subclass of NSUndoManager that is capable of keeping its own redundant memory of all the registrations upon it (by overriding registerUndoWithTarget:… and prepareWithInvocationTarget). With a trustable array of all the registrations, you could then impose your own policy for cleaning house at any time. I.e. you might say "if the target's class is from a framework I don't own, just remove it" … or be more specific and say you want to remove anything that matches the class WebEditorUndoTarget, for example.
回答3:
Last time I checked the NSUndoManager
had a method - (void)removeAllActions
. No need to specify action targets.
来源:https://stackoverflow.com/questions/8319146/removing-undo-actions-for-a-webviews-nsundomanager