Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performSelector with more than 2 objects

Tags:

objective-c

Is there a way to call [anObject performSelector]; with more than 2 objects? I know you can use an array to pass multiple arguments, but I was wondering if there was a lower level way to call a function I already have defined with more that 2 arguments without using a helper function with an nsarray of arguments.

like image 927
Mike Avatar asked Feb 27 '10 08:02

Mike


2 Answers

Either (1) Use an NSInvocation or (2) directly use objc_msgSend.

objc_msgSend(target, @selector(action:::), arg1, arg2, arg3);

(Note: make sure all arguments are id's, otherwise the arguments might not be sent correctly.)

like image 106
kennytm Avatar answered Sep 19 '22 08:09

kennytm


You can extend the NSObject class like this:

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

(See NSObjectAdditions from the Three20 project.) Then you could even extend the above method to use varargs and nil-terminated array of arguments, but that’s overkill.

like image 42
zoul Avatar answered Sep 18 '22 08:09

zoul