美文网首页
用NSInvocation来实现对象的任意方法的调用

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

作者: 李华光 | 来源:发表于2022-01-27 13:53 被阅读0次

用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来实现对象的任意方法的调用

      本文链接:https://www.haomeiwen.com/subject/oklahrtx.html