1

我正在尝试使用 NSInvocation 调用对象上的方法并将其sender作为参数发送。下面的代码调用了 mthod,但似乎传递给 mthod 的对象并不是真正的 self 对象

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

3 回答 3

2

请参阅分布式对象编程指南中的“使用 NSInvocation” 。


根据新问题进行编辑 *

我假设上面会这样调用:

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

在这种情况下,最终消息将是:

[target doSomething:foo];
于 2011-07-19T02:56:10.487 回答
2

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

于 2014-01-09T09:27:58.343 回答
1

你为什么不直接使用

   [target performSelector:selector withObject:self];

???selector什么时候@selector(foo:),这相当于

   [target foo:self];

NSInvocation在你的情况下是一个矫枉过正,在我看来。

于 2011-07-19T04:39:41.090 回答