How to "pass on" a variable number of arguments to NSString's +stringWithFormat:

Zoran Simic picture Zoran Simic · Sep 14, 2009 · Viewed 8.4k times · Source

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

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?

Answer

newacct picture newacct · Sep 14, 2009

initWithFormat:arguments:

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