Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass variable arguments to another method?

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 } 
like image 293
g.revolution Avatar asked Mar 06 '10 07:03

g.revolution


People also ask

How do you pass variables as an argument?

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.

How do you pass variable arguments in C++?

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.

Can we pass a variable argument?

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 .


2 Answers

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]); } 
like image 87
Till Avatar answered Sep 23 '22 16:09

Till


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]); } 
like image 35
kennytm Avatar answered Sep 25 '22 16:09

kennytm