如何将变量数量的参数“传递”给NSString的+stringWithFormat:

时间:2022-03-27 04:44:58

I would like to write a function in Objective-C such as the one below, that takes a variable number of arguments, and passes those arguments on to +stringWithFormat:. I know about vsnprintf, but that would imply converting the NSString 'format' to C and back (and would also mean converting the formatting placeholders within it as well...).

我想用Objective-C编写一个函数,比如下面的函数,它接受可变数量的参数,并将这些参数传递给+stringWithFormat:。我知道vsnprintf,但这意味着将NSString 'format'转换为C并返回(也意味着将其中的格式化占位符转换为…)。

The code below compiles, but of course does not behave as I want :)

下面的代码会编译,但是当然不会按照我的意愿运行:)

NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [NSString stringWithFormat:format, args];
    va_end(args);
    return s;
}

Basically: is there a va_list-friendly version of the +stringWithFormat: method, or is it possible to write one?

基本上:是否有一个具有va_list的版本的+stringWithFormat:方法,还是可以写一个?

1 个解决方案

#1


46  

initWithFormat:arguments:

initWithFormat:参数:

NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
    va_end(args);
    return s;
}

they don't seem to have a convenience constructor "stringWith..." version

他们似乎没有一个方便的构造函数“stringWith…”版本

#1


46  

initWithFormat:arguments:

initWithFormat:参数:

NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
    va_end(args);
    return s;
}

they don't seem to have a convenience constructor "stringWith..." version

他们似乎没有一个方便的构造函数“stringWith…”版本