1

I am trying to use NSInvocation to call a method on an object and send the sender as an argument. The code below calls the mthod but it seems like the object is passing to the mthod is not really self object

- (void)setTarget:(id)taret withAction:(SEL)selector
{
    NSMethodSignature *methodSignature = [target methodSignatureForSelector:action];
    _invocation = [[NSInvocation invocationWithMethodSignature:methodSignature] retain];

    _invocation.target = target;
    _invocation.selector = action;
    [_invocation setArgument:self atIndex:2];
}

- (void)callTargetWithSender
{
   [_invocation invoke];
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • 2
    Please don't completely rewrite your questions. It creates confusion later when people are searching and they find the answers don't match the question any more. If you have a new question, you should finish the first one and then ask the new question. – Rob Napier Jul 19 '11 at 15:00

3 Answers3

2

[invocation setArgument:(__bridge void *)(self) atIndex:2];

2

See "Using NSInvocation" in Distributed Objects Programming Guide.


EDIT BASED ON NEW QUESTION *

I assume the above will be called this way:

[foo setTarget:target withAction:@selector(doSomething:)];

In that case, the final message will be:

[target doSomething:foo];
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
1

Why don't you just use

   [target performSelector:selector withObject:self];

??? When selector is @selector(foo:), this is equivalent to

   [target foo:self];

NSInvocation in your situation is an overkill, in my opinion.

Yuji
  • 34,103
  • 3
  • 70
  • 88
  • Because In order to do performSelector I need to store both the selector and the target and I rather have 1 object (NSInvocation) to be responsible here. I am using an NSInvocation to store info about the method in ANOTHER object so that I can call it whenever I want. – aryaxt Jul 19 '11 at 04:41
  • 1
    There's nothing wrong with using `NSInvocation` for this. Do note, however, that creating an `NSInvocation` is crazy-expensive. Around 500x as slow as making a method call in my tests. They're not that expensive to invoke, just create. This is no problem in most cases, but it's worth remembering if you create them very often. Your use case is fine, though, and is what `NSInvocation` is designed for. `NSInvocation` also can handle an arbitrary number of parameters, unlike `performSelector:...` – Rob Napier Jul 19 '11 at 14:57