iPhone Development 101

iPhone 101

Code Tips

Resources

Links

Subscribe

TwitterRSSE-mail

More

iPhone Development 101: Objective-C:
Strings

The Objective-C class for strings is NSString. Strings are typically created by direct assignment or by calling one of the NSString class methods. As in other languages, strings are enclosed in "double quotes", however in Objective-C an NSString is prefixed by an @-sign:

NSString *newString = @"This is a string.";

There are a number of NSString class methods that create and return strings (refer to the NSString Class Reference documentation for a complete list). The one you're likely to use most often is stringWithFormat:

NSString *nameString = @"Fnord";
NSString *newString = [NSString stringWithFormat:@"The real %@ is %d", nameString, 23];
       // newString is now @"The real Fnord is 23"

Common string format specifiers are:

%@ another object. (this calls the :description verb on the specified object, which must then return an NSString.)
%d an integer number
%f, %.4f floating point number (with .n digits after the decimal place)

See the full list of String Format Specifiers in the String Programming Guide for Cocoa.

The length of a string can be obtained with the length method:

NSString *nameString = @"Fnord";
int nameLength = [nameString length];       // nameLength is 5

Common String Tasks

Additional References


TopHome