Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...