NSUndoManager基础知识

时间:2014-08-03 10:41:46

标签: objective-c xcode undo nsundomanager

我创建了一个有按钮的应用程序,当你按下它时,它会被禁用,撤消操作应该将它返回到先前的状态(启用它)。我使用NSUndoManager使这成为可能,但它不起作用。我的应用程序似乎缺少一些必要的东西,但我找不到确切的内容。

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

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我编辑了你的代码,我希望我的例子可以帮到你。

如果您仍有问题,请通知我=) 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