views:

723

answers:

1

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?

+13  A: 

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

newacct
Indeed! Thank you very much, I was looking at the wrong place (plus, I forgot the call to 'autorelease'). This works!
Zoran Simic
You're correct, they don't have a convenience method equivalent. I filed a Radar (#7025084) a few months ago requesting this exact thing. If you want this functionality, please report a bug requesting `+[NSString stringWithFormat:arguments:]` and reference this Radar number — duplicates (there is one already) are the best developers can do at "voting" on issues they consider to be important. http://bugreport.apple.com
Quinn Taylor
Note: To simplify triage, if you file a duplicate bug, please use component name "NSString" and version "X". Thanks!
Quinn Taylor
Apple's not likely to add a convenience constructor that amounts to a one-line wrapper around an existing -init... method.Just put it in a category on NSString. I do it all the time.
NSResponder
Just for public visibility: http://openradar.appspot.com/7025084
Quinn Taylor