Determining if an Objective-C method is variadic during runtime
Asked Answered
B

1

5

Is there a way to find out -- at runtime -- whether a given method is of variadic type? Something like method_getTypeEncoding(); that won't tell me whether a method accepts variable number of arguments. Or is there maybe a trick to tell so?

Benedic answered 16/7, 2012 at 19:54 Comment(4)
Can you explain a little more what context you'd want this information? I'm not sure of how exactly to find that at runtime but I also have never needed to building a lot of variadic methods. Basically what I'm getting at is perhaps you don't need to know and there is a larger problem. Perhaps but I could always be wrong too :)Solingen
What happens when you call method_getNumberOfArguments() on a veridic method? I've never tried it, but maybe it returns a special value (like -1 or something)? See also method_copyArgumentType().Heelpost
@Heelpost method_getNumberOfArguments returns minimal count, just as if it was normal method.Benedic
AFAIK it's not possible via method_*, NSMethodSignature, because variadic argument is encoded in the same way as non variadic argument. IOW (int)a, ... is encoded as 'i', which equals to simple (int)a (also 'i'). There's no support for introspection AFAIK. Maybe @bbum can shed some light on it ...Skirt
F
6

Robert's comment is correct. Consider:

@interface Boogity
@end
@implementation Boogity
- (void)methodWithOneIntArg:(int)a {;}
- (void)variadicMethodWithIDSentinel:(id)a, ... {;}
@end

Running strings on the resulting binary produces (there was also the stock main()):

strings asdfasdfasdf 
Boogity
methodWithOneIntArg:
variadicMethodWithIDSentinel:
v20@0:8i16
v24@0:8@16
Hello, World!

If I change the variadic method to be declared as - (void)variadicMethodWithIDSentinel:(int)a, ..., the strings output becomes:

Boogity
methodWithOneIntArg:
variadicMethodWithIDSentinel:
v20@0:8i16
Hello, World!

So, no, no way to tell.

Flotilla answered 17/7, 2012 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.