objective-cnsundomanagernsinvocation

NSUndoManager Delayed Argument Evaluation


I am trying to work with NSUndoManager's prepareWithInvocationTarget. I would like to have something like

[[self.undoManager prepareWithInvocationTarget:self] doSomethingWithObject:[self.aMutableArray objectAtIndex:0]]

where the argument of doSomethingWithObject is not evaluated until the undo method is called. In other words I don't want the argument to be the current first element of aMutableArray, but the first element of aMutableArray at the time of undo.

Is there a particular part of NSInvocation or NSMethodSignature that I should look at?


Solution

  • As in any method call, it just a question of what happens where. If you don't want [self.aMutableArray objectAtIndex:0] evaluated now, don't include it in the invocation expression! Instead, make the invocation expression a call to a method where that method will call [self.aMutableArray objectAtIndex:0]:

    [[self.undoManager prepareWithInvocationTarget:self] 
        doSomethingWithObjectAtIndex:0];
    

    ...where doSomethingWithObjectAtIndex: is where [self.aMutableArray objectAtIndex:0] is called.