如何使用va_args传递参数(可变参数,省略号) [英] How to use va_args to pass arguments on (variadic parameters, ellipsis)
问题描述
我无法理解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).
这是我的代码(实际上,我最终希望将其传递给NSString stringWithFormat,但是使NSLog正常工作就足够了):
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);
}
参数(或某些参数)通过,但是它有一些奇怪的值(输出为blah blah 1606412704
).我应该如何传递通过...
输入的值?
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 ...
?
推荐答案
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);
}
转发实际的...
(不是va_list
)的唯一方法是使用宏.例如:
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.
这篇关于如何使用va_args传递参数(可变参数,省略号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!