Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use va_args to pass arguments on (variadic parameters, ellipsis)

Tags:

objective-c

I can't get my head around the syntax for multiple arguments in Objective-C. I have seen this question, but the answer hasn't helped me (yet).

Here is my code (actually I will want to eventually pass to NSString stringWithFormat, but getting an NSLog to work would be good enough for now):

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     // Insert code here to initialize your application 
     [self log:@"blah blah %d", 32];
}


- (void)log:(NSString *)text, ... {
      va_list args;
      va_start(args, text);
      NSLog(text, args);
}

The argument (or some argument) comes through, but it's got some weird value (output is blah blah 1606412704). How should I pass the values that come in via ...?

like image 627
Dan Rosenstark Avatar asked Jun 29 '10 19:06

Dan Rosenstark


People also ask

How do you pass variable number of 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 variadic methods take any number of parameters?

A variadic function allows you to accept any arbitrary number of arguments in a function.

Is printf variadic function?

Variadic functions are functions (e.g. printf) which take a variable number of arguments. The declaration of a variadic function uses an ellipsis as the last parameter, e.g. int printf(const char* format, ...);. See variadic arguments for additional detail on the syntax and automatic argument conversions.


1 Answers

There's a variant of NSLog that accepts a va_list called NSLogv:

- (void) log:(NSString *)text, ... {
  va_list args;
  va_start(args, text);
  NSLogv(text, args);
  va_end(args);
}

The only way to forward the actual ... (not the va_list) is to use a macro. For example:

#define MyLog(f, ...) { \
NSLog(f, ##__VA_ARGS__); \
[someObject doSomething:f, ##__VA_ARGS__]; \
}

However, this should be used very sparingly, since macros can make code really obfuscated.

like image 135
Dave DeLong Avatar answered Oct 13 '22 03:10

Dave DeLong