views:

208

answers:

3

Newbie question.

I have a NSMutableArray that holds multiple objects (objects that stores bezier paths and related variables e.g. path colour ect.) These are properly released whenever the relevant -dealloc method is called. Each object is instansiated 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 (oterwise redo will not work) so if redo is never called, how do you properly release these object?

Hope that makes sense! Thanks!

A: 

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.

GalacticCowboy
Thanks. I'll keep it in mind.
Joe
+3  A: 

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.

Marc Charbonneau
Thanks! I figured keeping track in a separate list seemed like there should be a better way. I am using the NSUndoManager - just getting used to Cocoa and programming in Oop.
Joe
A: 

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.

Ashley Clark