StringWithFormat



Objective C allows us to create NSStrings using class method stringWithFormat.

StringWithFormat Syntax

[NSString stringWithFormat: @"%@", EXPR];
[NSString stringWithFormat: @"%d", INTEGEREXPR];

EXPR can be another NSString or object.
INTEGEREXPR is an integer.

The result of the above expression is NSString as shown in examples below.

StringWithFormat accepts a list of arguments which works similar to how arguments work in "printf" in standard C language. The difference being that StringWithFormat returns the value into NSString, but C's printf sends the result of the method to the standard output.

StringWithFormat Example 1:

int count = 5;
NSString *result;
result= [NSString stringWithFormat: @"Count is %d", count];

Now result will be a NSString containing "Count is 5".

StringWithFormat Example 2:

StringWithFormat recognizes the %@ conversion specification. You can use this to specify another NSString which is similar to %s in C string.

NSString *firstString;
NSString *secondString;
 
firstString = @"doing? ";
secondString = [NSString stringWithFormat: @"How are you %@", firstString];

This code will cause the "secondString" variable to now contain string "How are you doing?".

StringWithFormat Example 3:

NSString *firstName;
NSString *secondName;
 
firstName = @"David ";
secondName = @"Hilton ";
 
NSString *fullName = [NSString stringWithFormat:@"%@ %@",
    firstName,secondName];

Now, fullName would contain string "David Hilton".

%@ can also be used to output a description of an object (as returned by the NSObject's - description). This is helpful when debugging the application.

NSObject *obj = [anObject someMethod];
 
NSLog (@"The method returned: %@", obj);