performSelector支持多参数

默认的performSelector支持最多传递两个参数,要想传递超过两个的参数,需要使用NSInvocation来模拟performSelector的行为,如下:

- (id)performSelector:(SEL)aSelector withObjects:(NSArray *)argumentsArray

{

    NSMethodSignature *sig = [selfmethodSignatureForSelector:aSelector];

    if (sig)

    {

        NSInvocation *invocation = [NSInvocationinvocationWithMethodSignature:sig];

        [invocation setTarget:self];

        [invocation setSelector:aSelector];

        

        for (int i = 0; i < argumentsArray.count ; ++i)

        {

            id argument = [argumentsArray objectAtIndex:i];

            //此处+2不能漏

            [invocation setArgument:&argument atIndex:i + 2];

        }

        

        [invocation invoke];

        if (sig.methodReturnLength)

        {

            id anObject = nil;

            [invocation getReturnValue:anObject];

            return anObject;

        }

        

        return nil;

    }

    

    returnnil;

}

原文地址:https://www.cnblogs.com/lexingyu/p/3387323.html