I created a simple demo application with NSTextView and button, provided NSTextViewDelegate for textView and added action:
- (IBAction)actionButtonClicked:(id)sender { NSString *oldText = [[[self.textView textStorage] string] copy]; NSString *newText = @"And... ACTION!"; [[self.textView undoManager] registerUndoWithTarget:self.textView selector:@selector(setString:) object:oldText]; [[self.textView undoManager] setActionName:@"ACTION"]; [self.textView setString:newText]; }
Undo / redo works without problems if I change the text manually. But if I change the text using the action method, the undo will work as expected, but the replay will no longer work (nothing happens), and the undo manager seems to be scrambled ...
OK - to avoid problems with NSTextView, I created a model class, linked an NSTextView to it and moved the undo / redo to the model, but it shows the same behavior as before - what I am doing wrong - it should be easy, right?
#import "GFTextStore.h" @implementation GFTextStore @synthesize textVal = textVal_; -(void)changeText{ if (!undoMan_) { undoMan_ = [[[NSApplication sharedApplication] mainWindow] undoManager]; } NSAttributedString *oldText = [self.textVal copy]; NSString *tempStr = [[oldText string] stringByAppendingFormat:@"\n%@",[[NSCalendarDate date]description]]; NSAttributedString *newText = [[NSAttributedString alloc] initWithString:tempStr]; [self setTextVal:newText]; [undoMan_ registerUndoWithTarget:self selector:@selector(setTextVal:) object:oldText]; [undoMan_ setActionName:@"ACTION"]; } @end
cocoa undo-redo nstextview
user808667
source share