2

I made an app which has a button, when you press it, it becomes disabled and Undo action should return it to the previous state (enable it). I used NSUndoManager to make this possible, but it doesn't work. It seems I'm missing something essential in my app, but I can't find what exactly.

AppDelegate.h:

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
    NSUndoManager* undoManager;
}

@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSButton *button;
- (IBAction)Disable:(id)sender;

@end

AppDelegate.m:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

- (NSUndoManager*)windowWillReturnUndoManager:(NSWindow*)window
{
    return undoManager;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

}

- (id) init
{
    if(self = [super init])
        undoManager = [[NSUndoManager alloc]init];
    return self;
}


- (IBAction)Disable:(id)sender
{
    [[undoManager prepareWithInvocationTarget:self]Enable];
    [_button setEnabled:NO];
    if (![undoManager isUndoing])
        [undoManager setActionName:@"Disable"];
}

-(void)Enable
{
    [[undoManager prepareWithInvocationTarget:self]Disable:self];
    [_button setEnabled:YES];
    if (![undoManager isUndoing])
        [undoManager setActionName:@"Enable"];
}
@end

What am I doing wrong?

Yashman
  • 111
  • 1
  • 11

1 Answers1

3

I have edit your code and I Hope my example will help you.

Please notify me if you still have some problem with it =) screen

#import "AppDelegate.h"

@interface AppDelegate ()
{
    NSUndoManager* undoManager;
}
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSButton *button;
@property (weak) IBOutlet NSButton *undoButton;

@end

@implementation AppDelegate

- (NSUndoManager*)windowWillReturnUndoManager:(NSWindow*)window
{
    return undoManager;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    undoManager = [[NSUndoManager alloc]init];
    [self update];
}

- (IBAction)Disable:(id)sender
{
    [[undoManager prepareWithInvocationTarget:self]Enable];
    [_button setEnabled:NO];
    if (![undoManager isUndoing])
        [undoManager setActionName:@"Disable"];
    [self update];
}

- (IBAction)undo:(id)sender
{
    [undoManager undo];
    [self update];
}

-(void)Enable
{
    [[undoManager prepareWithInvocationTarget:self]Disable:self];
    [_button setEnabled:YES];
    if (![undoManager isUndoing])
        [undoManager setActionName:@"Enable"];
    [self update];
}

- (void)update
{
    self.undoButton.title = [undoManager canUndo]?@"Undo":@"Can't undo";
}

@end
Nuzhdin Vladimir
  • 1,714
  • 18
  • 36