Joe
Joe

Reputation: 173

Undo and Object release

Newbie question.

I have a NSMutableArray that holds multiple objects (objects that stores Bezier paths and related variables e.g. path colour etc.) These are properly released whenever the relevant -dealloc method is called. Each object is instantiated with +alloc/-init and added to the array. After adding them to the array I release the object and hence their retainCount=1 (due to the array). Thus, when the array is released, the objects are also properly deallocated.

But, I'm also implementing an undo/redo mechanism that removes/adds these objects from/to the NSMutable array.

My question is, when an undo removes the object from the array, they are not released (otherwise redo will not work) so if redo is never called, how do you properly release these object?

Hope that makes sense! Thanks!

Upvotes: 1

Views: 496

Answers (3)

Ashley Clark
Ashley Clark

Reputation: 8823

If you're using NSUndoManager then when you place a new undo action on the stack the redo stack is cleared and at that point any items that were on the redo stack are released.

If you want to clear the stacks earlier you can call -removeAllActions or -removeAllActionsWithTarget: but both of those will clear both the undo and redo stacks.

Upvotes: 0

Marc Charbonneau
Marc Charbonneau

Reputation: 40517

You don't need to keep a reference to the object you're working with. When you add an operation to the undo stack (see NSUndoManager registerUndoWithTarget:) it will retain the argument for you. For instance, if you add an object using addObject:(id)obj in your code, you would register it with NSUndoManager using your removeObject: action and obj as the argument. The undo manager will retain that object until the action is cleared from the undo stack. If you override dealloc in your object and put in an NSLog() message, you'll see exactly how it works.

If you're not using NSUndoManager, start! It makes it very easy to get proper undo management in OS X, and it's very flexible.

Upvotes: 3

GalacticCowboy
GalacticCowboy

Reputation: 11759

Maintain a separate list of potential redo actions; move an item from the active list to this one. Only release them once they are "unreachable" (the user performs some other action that invalidates the redo list). You then still have a reference to these items that can be cleaned up if they are never put back on the "active" stack.

Upvotes: 0

Related Questions