How to Format an NSString

Dec 19, 2009   //   by Derek van Vliet   //   Development  //  2 Comments

It’s back to basics with today’s advent tip. I would be surprised if anything short of ALL developers have had a need to format strings at one time or another. iPhone app development is no exception.

String formatting allows you to build a string based on a template and varying types of values. For example, if I am keeping track of a player’s score as an integer and I want to display a string to the player that celebrates their score by saying “You scored 2600! Way to go!”, then I need string formatting to get the correct score in the middle of that string.

How to Do It

Below is an example of how to build the above NSString. This example formats a string with an integer in it using the %i format specifier.

int score = 2600;
NSString * scoreString = [NSString stringWithFormat:@"You scored %i! Way to go!",score];

Format Specifiers

But string formatting doesn’t stop at putting integers in strings. Below are some of the most common format specifiers for other value types:

Specifier Purpose
%i integer
%f float
%@ Objective-C object (commonly used to specify another NSString)
%x hexadecimal


Leave a comment

Our Games