Showing posts with label NSString initWithFormat arguments example. Show all posts
Showing posts with label NSString initWithFormat arguments example. Show all posts

Saturday, May 18, 2013

NSString initWithFormat arguments example ios


[NSString initWithFormat arguments]

Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
- (id)initWithFormat:(NSString *)format arguments:(va_list)argList
Parameters
format
A format string. See “Formatting String Objects” for examples of how to use this method, and “String Format Specifiers” for a list of format specifiers. This value must not be nil.[NSString initWithFormat arguments]

Important: Raises an NSInvalidArgumentException if format is nil.
argList
A list of arguments to substitute into format.
Return Value of [NSString initWithFormat arguments]
An NSString object initialized by using format as a template into which the values inargList are substituted according to the user’s default locale. The returned object may be different from the original receiver.
Discussion
Invokes initWithFormat:locale:arguments: with nil as the locale.
[NSString initWithFormat arguments] example
void print (NSString *format, ...) {
    va_list args;
    va_start(args, format);

    fputs([[[[NSString alloc] initWithFormat:format arguments:args] autorelease] UTF8String], stdout);

    va_end(args);
}
[NSString initWithFormat arguments] example
NSString* format = @"Item %s and Item %s"; // Retrieved elsewhere
NSArray* args = [NSArray arrayWithObjects:@"1", @"2", nil]; // Retrieved elsewhere

// http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
char* argsList = (char*) malloc(sizeof(NSString*) * args.count);
[args getObjects:(id*) argsList];
NSString* message = [[[NSString alloc] initWithFormat:format arguments:argsList] autorelease];
free(argsList);
[NSString initWithFormat arguments] example
void log(NSString* format, ...)
{
    va_list arguments;
    va_start(list, format);

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

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

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