When would initWithFormat:arguments: be used?

The NSString method initWithFormat:arguments: takes a va_list as an argument. I can't figure out when it would be used (or even how to use it). Why would Apple add such a method when the regular initWithFormat: is much more user-friendly?


You can't pass a dynamic list of format arguments to -initWithFormat:. For example, if you wanted to implement -stringByAppendingFormat: yourself without -initWithFormat:arguments:, you'd have a job of it. With the va_list version, you could do it:

- (NSString *)stringByAppendingFormat:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    NSString * result = [self stringByAppendingString:[NSString stringWithFormat:format arguments:args]];
    return result;

It's useful when your own function or method uses variadic arguments, because in that case it is impossible to use the vanilla initWithFormat: method.

For instance, the following (useless) example snippet:

void log(NSString* format, ...)
    va_list arguments;
    va_start(arguments, format);

    // impossible:
    // NSString* formattedString = [[NSString alloc] initWithFormat: ???];

    // possible
    va_list argsCopy;
    va_copy(argsCopy, arguments);
    NSString* formattedString = [[NSString alloc] initWithFormat:format arguments:argsCopy];    

    // do something cool with your string
    NSLog(@"%@", formattedString);

I would say without looking further into it that Apple provide NSString initWithFormat: as a utility method on top of NSString initWithFormat:arguements: meaning the short version just ends up calling the longer one.

There's also [NSString stringWithFormat:] that can return an autoreleased NSString, saving you the alloc call if you don't need the string around for long.

Need Your Help

Scope and MySQLi binding

php mysqli

I've been using the old MySQL library for PHP for ages now and I've finally caved into using MySQLi. Prepared statements seem very useful, so I'm trying to get the hang out them.

creating a jar for a project in Eclipse

java eclipse jar

I am using Eclipse and I have just started working on a project that needs another project (say pjkt) to function. The pjkt project files are stored in a specific folder. I would like to create a jar