用NSInvocation来实现对象的任意方法的调用

用NSInvocation来实现对象的任意方法的调用

- (int)sumABC {
    SEL sel = @selector(sumWithA:B:C:);
    NSMethodSignature *methodSignature = [self methodSignatureForSelector:sel];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
    [invocation setSelector:sel];
    [invocation setTarget:self];
    
    int a = 1, b = 2, c = 3;
    [invocation setArgument:&a atIndex:2];
    [invocation setArgument:&b atIndex:3];
    [invocation setArgument:&c atIndex:4];
    
    [invocation invoke];
    
    int sum;
    [invocation getReturnValue:&sum];
    
    NSLog(@"sum is %d", sum);
    
    return sum;
}

- (int)sumWithA:(int)A B:(int)B C:(int)C {
    return A + B + C;
}

你可能感兴趣的:(用NSInvocation来实现对象的任意方法的调用)