performSelector包含2个以上的对象

Mik*_*ike 16 objective-c

有没有办法调用[anObject performSelector]; 超过2个对象?我知道你可以使用一个数组来传递多个参数,但我想知道是否有一个较低级别的方法来调用一个我已经用更多的2个参数定义的函数,而不使用带有nsarray参数的辅助函数.

ken*_*ytm 49

(1)使用NSInvocation或(2)直接使用objc_msgSend.

objc_msgSend(target, @selector(action:::), arg1, arg2, arg3);
Run Code Online (Sandbox Code Playgroud)

(注意:确保所有参数都是id's,否则参数可能无法正确发送.)

  • 使用objc_msgSend时,您需要按照以下方式#import <objc/message.h>:http://stackoverflow.com/questions/4896510/how-to-import-nsobjcruntime-h-to-use-objc-msgsend (12认同)

zou*_*oul 14

您可以NSObject像这样扩展类:

- (id) performSelector: (SEL) selector withObject: (id) p1
       withObject: (id) p2 withObject: (id) p3
{
    NSMethodSignature *sig = [self methodSignatureForSelector:selector];
    if (!sig)
        return nil;

    NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
    [invo setTarget:self];
    [invo setSelector:selector];
    [invo setArgument:&p1 atIndex:2];
    [invo setArgument:&p2 atIndex:3];
    [invo setArgument:&p3 atIndex:4];
    [invo invoke];
    if (sig.methodReturnLength) {
        id anObject;
        [invo getReturnValue:&anObject];
        return anObject;
    }
    return nil;
}
Run Code Online (Sandbox Code Playgroud)

(参见Three20项目中的NSObjectAdditions.)然后你甚至可以扩展上面的方法来使用varargs和nil-terminated参数数组,但这太过分了.