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

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

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 ...?

回答1:

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.



回答2:

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); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!