i have googled and came to know that how to use the variable arguments. but i want to pass my variable arguments to another method. i m getting errors. how to do that ?
-(void) aMethod:(NSString *) a, ... { [self anotherMethod:a]; // i m doing this but getting error. how to pass complete vararg to anotherMethod }
Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg. h header file. Use va_arg macro and va_list variable to access each item in argument list.
Variable number of arguments in C++Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Create a va_list type variable in the function definition. This type is defined in stdarg. h header file.
If you've converted the variable arguments to a va_list , you can pass the va_list to another function that only takes a va_list , but that function (or one that it calls) must have some way of knowing what's in the va_list .
AFAIK ObjectiveC (just like C and C++) do not provide you with a syntax that allows what you directly have in mind.
The usual workaround is to create two versions of a function. One that may be called directly using ... and another one called by others functions passing the parameters in form of a va_list.
.. [obj aMethod:@"test this %d parameter", 1337); [obj anotherMethod:@"test that %d parameter", 666); .. -(void) aMethod:(NSString *)a, ... { va_list ap; va_start(ap, a); [self anotherMethod:a withParameters:ap]; va_end(ap); } -(void) anotherMethod:(NSString *)a, ... { va_list ap; va_start(ap, a); [self anotherMethod:a withParameters:ap]; va_end(ap); } -(void) anotherMethod:(NSString *)a withParameters:(va_list)valist { NSLog([[[NSString alloc] initWithFormat:a arguments:valist] autorelease]); }
You cannot pass variadic arguments directly. But some of these methods provide an alternative that you can pass a va_list
argument e.g.
#include <stdarg.h> -(void)printFormat:(NSString*)format, ... { // Won't work: // NSString* str = [NSString stringWithFormat:format]; va_list vl; va_start(vl, format); NSString* str = [[[NSString alloc] initWithFormat:format arguments:vl] autorelease]; va_end(vl); printf("%s", [str UTF8String]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With