iOS中,如何做到未知参数数量的反射

本文介绍了在iOS开发中如何利用反射处理未知数量的参数进行方法调用,但要注意该方法仅适用于对象参数,不支持数值或指针类型。通过示例代码和StackOverflow上的参考资料,开发者可以学习到如何进行此类反射操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里我是参考网上资料的一个处理,直接贴代码

void invokeSelector(id object, SEL selector, NSArray *arguments)
{
    NSMethodSignature *signature = [object methodSignatureForSelector:selector];

if (signature.numberOfArguments == 0) {
    return; //@selector未找到
}

if (signature.numberOfArguments > [arguments count]+2) {
    return; //传入arguments参数不足。signature至少有两个参数,self和_cmd
}

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:object];
[invocation setSelector:selector];

for(int i=0; i<[arguments count]; i++)
{
    id arg = [arguments objectAtIndex:i];
    [invocation setArgument:&arg atIndex:i+2]; // The first two arguments are the hidden arguments self and _cmd
}

[invocation invoke]; // Invoke the selector
}

注意这个方法有个缺陷,只能传入对象参数,不能传入数值、指针等类型。如果有其他需求,你可以自己改造方法

调用示例如下

@implementation AppDelegate

- (void)printTest:(id)a and:(id)b and:(id)c {
NSLog(@"print a %@ b %@ c %@", a, b, c);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

invokeSelector(self, @selector(printTest:and:and:), @[@1,@3,@"hehehe"]);

return YES;
}
@end

参考:http://stackoverflow.com/questions/5788346/calling-a-selector-with-unknown-number-of-arguments-using-reflection-introspec

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值