【问题标题】:NSUndoManager won't undo editing of a NSMutableDictionaryNSUndoManager 不会撤消对 NSMutableDictionary 的编辑
【发布时间】:2011-02-24 08:34:42
【问题描述】:

我遇到了撤消操作的问题。以下代码不会撤消 removeObjectForKey: 操作,但重做操作 setObject:ForKey: 有效。

 - (void) insertIntoDictionary:(NSBezierPath *)thePath
{
 [[[window undoManager] prepareWithInvocationTarget:self] removeFromDictionary:thePath];

 if(![[window undoManager] isUndoing])
  [[window undoManager] setActionName:@"Save Path"];

 NSLog(@"Object id is: %d and Key id is: %d", [currentPath objectAtIndex:0], thePath);

 [colorsForPaths setObject:[currentPath objectAtIndex:0] forKey:thePath];
}

- (void) removeFromDictionary:(NSBezierPath *)thePath
{
 [[[window undoManager] prepareWithInvocationTarget:self] insertIntoDictionary:thePath];

 if(![[window undoManager] isUndoing])
  [[window undoManager] setActionName:@"Delete Path"];

 NSLog(@"Object id is: %d and Key id is: %d", [colorsForPaths objectForKey:thePath], thePath);

 [colorsForPaths removeObjectForKey:thePath];

}

控制台上的输出如下:

// Before setObject:ForKey:
Object id is: 1183296 and Key id is: 1423872

// Before removeObjectForKey:
UNDO
Object id is: 0 and Key id is: 1423872

我不明白为什么 Object id 不同,尽管 Key id 保持不变。 NSMutableDictionary 对象是否有一些特殊的撤消/重做处理?

谢谢 索尼克

【问题讨论】:

    标签: objective-c cocoa undo redo


    【解决方案1】:

    听起来 NSUndoManager 正在做它的工作,但是当需要删除该值时,字典中没有 NSBezierPath 键的对象。我的猜测是 NSBezierPath 用作字典键是不安全的。您用作键的 NSBezierPath 对象可能在赋值和撤消之间的某个地方发生了变异,这意味着它的 hash 方法在您到达 removeFromDictionary: 时已经不同,并且您不再拥有有意义的字典键。相反,请尝试使用与贝塞尔路径相关联的 NSString 或 NSNumber 作为字典键。

    【讨论】:

    • 感谢您的意见。其实我不确定这是否真的是问题所在。一方面,我在不同的文件(视图)中确实有相同的调用 [colorsForPaths objectForKey:thePath],它返回正确的对象,但另一方面,重做操作记录正确的 NSBezierPath id 并在字典中插入正确的对象即使该对象随后在字典中出现两次并且没有被新的重做(相同)对象覆盖。
    【解决方案2】:

    在一个示例中,您记录了[currentPath objectAtIndex:0] 的地址,而在另一个示例中,您记录了字典中任意键(甚至不是值,而是随机键)的地址。我没有理由在代码中看到为什么它们应该是同一件事。

    【讨论】:

    • 啊该死,对此感到抱歉...在玩代码时留下了 sn-p。我想我累了:)我现在已经更正了代码,但结果仍然无法正常工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    相关资源
    最近更新 更多