Does NSUndoManager retain objects?

廉价感情. 提交于 2019-12-12 05:33:38

问题


I do the following:

    Path2D *pathToRemove = [path copy];
    [[[self undoManager] prepareWithInvocationTarget:self] removePath:pathToRemove atIndex:index];
[pathToRemove autorelease];

I also have a clear button that does:

[undoManager removeAllActions];

Problem is that the removeAllActions crashes the app. When I removed the [pathToRemove autorelease], it worked (or at least didn't crash. It could still be a memory leak). I guess I was assuming that the undoManager retained 'pathToRemove' when passed in the 'prepareWithInvocationTarget' call.

Is that not the case? If that is not the case then the crash could happen because the call to 'removeAllActions' is releasing the 'PathToRemove' object. But that would mean it is a bug in NSUndoManager which is highly unlikely.

I can say that my copyWithZone implementation is not likely to be the culprit either since NSLog outputs for '[pathToRemove description]' and '[path description]' show different addresses as expected.

Any help would be appreciated. Thanks.


回答1:


According to the documentation, the prepareWithInvocationTarget: method doesn't retain the arguments passed to it. From the NSUndoManager documentation, it appears that it simply captures the NSInvocation and later replays it. NSInvocationobjects don't retain the objects in their arguments unless specifically asked to do so.

That doesn't quite explain the crash, because removeAllActions is just supposed to clear the undo stack and not do anything to the objects.

Hope this helps some in tracking down the source of the crash.




回答2:


In my experience, it's not a release/retain issue. You've to clear the stack after the Undo/Redo Operation. To do this you can register your viewController for the NSUndoManagerDidUndoChangeNotification notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearUndoRedoStack) name:NSUndoManagerDidUndoChangeNotification object:nil];

and then clear the stack onto the specified method:

- (void)clearUndoRedoStack {
    [undoManager removeAllActions];
}


来源:https://stackoverflow.com/questions/4252428/does-nsundomanager-retain-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!