Sunday, May 12, 2013

NSString stringWithFormat example ios


stringWithFormat:

Returns a string created by using a given format string as a template into which the remaining argument values are substituted.
+ (id)stringWithFormat:(NSString *)format, ...
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.

Important: Raises an NSInvalidArgumentException if format is nil.
...
A comma-separated list of arguments to substitute into format.
Return Value of [NSString stringWithFormat]
A string created by using format as a template into which the remaining argument values are substituted according to the canonical locale.
Discussion of [NSString stringWithFormat]
This method is similar to localizedStringWithFormat:, but using the canonical locale to format numbers. This is useful, for example, if you want to produce “non-localized” formatting which needs to be written out to files and parsed back later.
Example of [NSString stringWithFormat]
NSString *lastName = (NSString *)ABRecordCopyValue(personRef, kABPersonLastNameProperty);
cell.text = [NSString stringWithFormat:@"%@%@",lastName?[NSString stringWithFormat:@"%@ ",lastName]:@"",(NSString *)ABRecordCopyValue(personRef, kABPersonFirstNameProperty)?:@""];
Example of [NSString stringWithFormat]
NSString *parameter1 = @"1";
NSString *parameter2 = @"2";

NSString *myString;
myString = [NSString stringWithFormat:@"I want to print parameter1 here: %1$@, parameter2 here: %2$@ and now access parameter1 again: %1$@ _without_ passing it again.",parameter1, parameter2];
Example of [NSString stringWithFormat]
NSString* format = [NSString stringWithFormat:@"%%0%dd", maxLength];
NSString *s = [NSString stringWithFormat:format, 10];
NSLog(@"%@", s);