如何避免NSUndoManager中的空撤消组?

时间:2013-01-08 06:56:48

标签: nsundomanager

我在undoManager undo / redo stacks中得到了空的undo / redo组。在很多情况下,将canUndo / canRedo设为TRUE。 如何避免这种情况?

2 个答案:

答案 0 :(得分:2)

我避免这种情况的一种方法是检测何时创建空事件,然后静默撤消它。在NSUndoManager的子类中:

@interface MyUndoManager : NSUndoManager
@property BOOL haveReceivedInvocationPreparation;
@end

@implementation MyUndoManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.haveReceivedInvocationPreparation = NO;
    }
    return self;
}

- (void)endUndoGrouping {
    [super endUndoGrouping];

    if (self.groupingLevel == 0) {
        if (!self.haveReceivedInvocationPreparation && !self.isUndoing) {
            [self disableUndoRegistration];
            [self undo];
            [self enableUndoRegistration];
        }
        self.haveReceivedInvocationPreparation = NO;
    }
}

- (id)prepareWithInvocationTarget:(id)target {
    self.haveReceivedInvocationPreparation = YES;
    return [super prepareWithInvocationTarget:target];
}

@end

到目前为止,这似乎运作良好,我还没有看到任何奇怪的行为。

答案 1 :(得分:0)

AFAIK,您无法避免NSUndoManager将空撤消组计为有效的撤消操作。 一种解决方案是使用GCUndoManager,它试图解决空组的问题,请参阅http://apptree.net/gcundomanager.htm