aryaxt
aryaxt

Reputation: 77596

Objective C - NSInvocation passing self as sender?

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];
}

Upvotes: 1

Views: 1041

Answers (3)

user3176858
user3176858

Reputation: 31

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

Upvotes: 2

Rob Napier
Rob Napier

Reputation: 299345

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];

Upvotes: 2

Yuji
Yuji

Reputation: 34185

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.

Upvotes: 1

Related Questions