performSelector with more than 2 objects

前端 未结 3 1509
旧时难觅i
旧时难觅i 2020-12-23 16:45

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 lowe

3条回答
  •  鱼传尺愫
    2020-12-23 16:59

    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.

提交回复
热议问题