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

前端 未结 2 989
心在旅途
心在旅途 2020-12-16 02:55

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 (act

相关标签:
2条回答
  • 2020-12-16 03:35

    You could use -[NSString initWithFormat:arguments:]:

    - (void)log:(NSString *)text, ...
    {
        va_list args;
        va_start(args, text);
        NSString *log_msg = [[[NSString alloc] initWithFormat:text arguments:args] autorelease];
        NSLog(@"%@", log_msg);
    }
    
    0 讨论(0)
  • 2020-12-16 03:41

    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.

    0 讨论(0)
提交回复
热议问题