Search code examples
iphonensundomanager

iPhone - NSUndoManager + NSInvocation + object released = crash


I am building a undo/redo functionality for my app. I am using the NSInvocation method of NSUndoManager.

This is how I build the invocation

NSNumber *firstState = [NSNumber numberWithInt:fsNumber];
NSInvocation *initialState = [self restoreStateInvocation:firstState];
// ... the code continues...

these are the methods relates

- (NSInvocation *) restoreStateInvocation:(NSNumber*)number {
  NSMethodSignature *executeMethodSignature = [self methodSignatureForSelector:
                                                 @selector(makeUNDO:)];
  NSInvocation *moveInvocation = [NSInvocation invocationWithMethodSignature: executeMethodSignature];
  [moveInvocation setTarget:self];
  [moveInvocation setSelector:@selector(makeUNDO:)];

  [moveInvocation setArgument:&number atIndex:2];
  return moveInvocation;
}


- (void) makeUNDO:(NSNumber*)number {

  int num = (int)[number intValue];
  // code crashes at this line... number appears to be deallocated at this time
  //
...
}

when the UNDO/REDO calls initialState the app crashes on the first line of makeUNDO, as pointed on the code.

how can I retain number without leaking?

thanks.


Solution

  • the correct answer is to add the following line to restoreStateInvocation...

    [moveInvocation retainArguments];