When would initWithFormat:arguments: be used?
The NSString method initWithFormat:arguments: takes a va_list as an argument. I can't f开发者_Python百科igure 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]];
va_end(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);
va_end(argsCopy);
va_end(arguments);
}
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.
精彩评论