Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top