Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Foundation Classes

If you’re new to Objective-C, there are a few key classes you absolutely need to be familiar with before moving forward. These include strings, numbers, and collections, and they provide critical application building blocks. The NSString class, for example, provides the workhorse for nearly all text manipulation in Objective-C. However, it, like other fundamental classes, is not defined in Objective-C itself. It is part of the Foundation framework, which offers nearly all the core utility classes you use on a day-to-day basis.

Foundation provides over a dozen kinds of object families and hundreds of object classes. These range from value objects that store numbers and dates, to strings that store character data; from collections that store other objects, to classes that access the file system and retrieve data from URLs. Foundation is often referred to (slightly inaccurately) as Cocoa. (Cocoa and its iPhone-device-family equivalent Cocoa Touch actually include all the frameworks for OS X programming.) To master Foundation is to master Objective-C programming, and thorough coverage of the subject demands an entire book of its own.

As this section cannot offer an exhaustive introduction to Foundation classes, you’re about to be introduced to a quick-and-dirty survival overview. Here are the classes you need to know about and the absolutely rock-core ways to get started using them. You find extensive code snippets that showcase each of the classes to give you a jumping-off point if, admittedly, not a mastery of the classes involved.

Strings

Cocoa strings store character data, just as their cousins the (char *) C strings do. They are, however, objects and not byte arrays. Unlike C, the core NSString class is immutable in Cocoa. That is, you can use strings to build other strings, but you can’t edit the strings you already own. String constants are delineated by quote marks and the @ character. Here is a typical string constant, which is assigned to a string variable:

NSString *myString = @"A string constant";

Building Strings

You can build strings using formats, much as you would using sprintf. If you’re comfortable creating printf statements, your knowledge transfers directly to string formats. Use the %@ format specifier to include objects in your strings. String format specifiers are thoroughly documented in the Cocoa String Programming Guide, available via Xcode’s documentation window (Command-Option-?). The most common formats are listed in Table 3-1.

NSString *myString = [NSString stringWithFormat:
    @"The number is %d", 5];

To create new strings, you can append strings together. This call outputs “The number is 522” and creates a new instance built from other strings:

NSLog(@"%@", [myString stringByAppendingString:@"22"]);

Appending formats provides even more flexibility. You specify the format string and the components that build up the result:

NSLog(@"%@", [myString stringByAppendingFormat:@"%d", 22]);

Length and Indexed Characters

Every string can report its length (via length) and produce an indexed character on demand (via characterAtIndex:). The two calls shown here output 15 and e, respectively, based on the previous @"The number is 5" string. Cocoa characters use the unichar type, which store Unicode-style characters.

NSLog(@"%d", myString.length);
printf("%c", [myString characterAtIndex:2]);

Converting to and from C Strings

The realities of normal C programming often crop up despite working in Objective-C. Being able to move back and forth between C strings and Cocoa strings is an important skill. Convert an NSString to a C string either by sending UTF8String or cStringUsingEncoding:. These are equivalent, producing the same C-based bytes:

printf("%s\n", [myString UTF8String]);
printf("%s\n", [myString cStringUsingEncoding: NSUTF8StringEncoding]);

You can also go the other way and transform a C string into an NSString by using stringWithCString: encoding. The examples here use UTF-8 encoding, but Objective-C supports a large range of options, including ASCII, Japanese, Latin, Windows-CP1251, and so forth.

NSLog(@"%@", [NSString stringWithCString:"Hello World"
    encoding: NSUTF8StringEncoding]);

Writing Strings to and Reading Strings from Files

Writing to and reading strings from the local file system offers a handy way to save and retrieve data. This snippet shows how to write a string to a file:

NSString *myString = @"Hello World";
NSError *error;
NSString *path = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents/file.txt"];
if (![myString writeToFile:path atomically:YES
     encoding:NSUTF8StringEncoding error:&error])
{
    NSLog(@"Error writing to file: %@", [error localizedDescription]);
    return;
}
NSLog(@"String successfully written to file");

The path for the file is NSHomeDirectory(), a function that returns a string with a path pointing to the application sandbox. Notice the special append method that properly appends the Documents/file.txt subpath.

In Cocoa, most file access routines offer an atomic option. When you set the atomically parameter to YES, the iOS SDK writes the file to a temporary auxiliary and then renames it into place. Using an atomic write ensures that the file avoids corruption.

The request shown here returns a Boolean, namely YES if the string was written or NO if it was not. Should the write request fail, this snippet logs the error using a language-localized description. It uses an instance of the NSError class to store that error information and sends the localizedDescription selector to convert the information into a human-readable form. Whenever iOS methods return errors, use this approach to determine which error was generated.

Reading a string from a file follows a similar form but does not return the same Boolean result. Instead, check to see whether the returned string is nil, and if so display the error that was returned:

NSString *inString = [NSString stringWithContentsOfFile:path
    encoding:NSUTF8StringEncoding error:&error];
if (!inString)
{
    NSLog(@"Error reading from file % %@", [path lastPathComponent],
        [error localizedDescription]);
    return;
}
NSLog(@"String successfully read from file");
NSLog(@"%@", inString);

Accessing Substrings

Cocoa offers a number of ways to extract substrings from strings. Here’s a quick review of some typical approaches. As you’d expect, string manipulation is a large part of any flexible API, and Cocoa offers many more routines and classes to parse and interpret strings than the few listed here. This quick NSString summary skips any discussion of NSScanner, NSXMLParser, and so forth.

Converting Strings to Arrays

You can convert a string into an array by separating its components across some repeated boundary. This example chops the string into individual words by splitting around spaces. The spaces are discarded, leaving an array that contains each number word.

NSString *myString = @"One Two Three Four Five Six Seven";
NSArray *wordArray = [myString componentsSeparatedByString: @" "];
NSLog(@"%@", wordArray);
Requesting Indexed Substrings

You can request a substring from the start of a string to a particular index, or from an index to the end of the string. These two examples return @"One Two" and @"Two Three Four Five Six Seven", respectively, using the to and from versions of the indexed substring request. As with standard C, array and string indexes start at 0.

NSString *sub1 = [myString substringToIndex:7];
NSLog(@"%@", sub1);

NSString *sub2 = [myString substringFromIndex:4];
NSLog(@"%@", sub2);
Generating Substrings from Ranges

Ranges let you specify exactly where your substring should start and stop. This snippet returns @"Tw", starting at character 4 and extending two characters in length. NSRange provides a structure that defines a section within a series. You use ranges with indexed items such as strings and arrays.

NSRange r;
r.location = 4;
r.length = 2;
NSString *sub3 = [myString substringWithRange:r];
NSLog(@"%@", sub3);

Search and Replace with Strings

With Cocoa, you can easily search a string for a substring. Searches return a range, which contain both a location and a length. Always check the range location. The location NSNotFound means the search failed. This returns a range location of 18, with a length of 4.

NSRange searchRange = [myString rangeOfString:@"Five"];
if (searchRange.location != NSNotFound)
    NSLog(@"Range location: %d, length: %d", searchRange.location, searchRange.length);

Once you’ve found a range, you can replace a subrange with a new string. The replacement string does not need to be the same length as the original; thus, the result string may be longer or shorter than the string you started with:

NSLog(@"%@", [myString stringByReplacingCharactersInRange:
    searchRange withString: @"New String"]);

A more general approach lets you replace all occurrences of a given string. This snippet produces @"One * Two * Three * Four * Five * Six * Seven" by swapping out each space for a space-asterisk-space pattern:

NSString *replaced = [myString stringByReplacingOccurrencesOfString:
    @" " withString: @" * "];
NSLog(@"%@", replaced);

Changing Case

Cocoa provides three simple methods that change a string’s case. Here, these three examples produce a string all in uppercase, all in lowercase, and one where every word is capitalized (“Hello World. How Do You Do?”). Because Cocoa supports case-insensitive comparisons, you rarely need to apply case conversions when testing strings against each other.

NSString *myString = @"Hello world. How do you do?";
NSLog(@"%@",[myString uppercaseString]);
NSLog(@"%@",[myString lowercaseString]);
NSLog(@"%@",[myString capitalizedString]);

Testing Strings

The iOS SDK offers many ways to compare and test strings. The three simplest check for string equality and match against the string prefix (the characters that start the string) and suffix (those that end it). More complex comparisons use NSComparisonResult constants to indicate how items are ordered compared with each other.

NSString *s1 = @"Hello World";
NSString *s2 = @"Hello Mom";
NSLog(@"%@ %@ %@", s1, [s1 isEqualToString:s2] ?
    @"equals" : @"differs from", s2);
NSLog(@"%@ %@ %@", s1, [s1 hasPrefix:@"Hello"] ?
    @"starts with" : @"does not start with", @"Hello");
NSLog(@"%@ %@ %@", s1, [s1 hasSuffix:@"Hello"] ?
    @"ends with" : @"does not end with", @"Hello");

Extracting Numbers from Strings

Convert strings into numbers by using a Value method. These examples return 3, 1, 3.141592, and 3.141592, respectively.

NSString *s1 = @"3.141592";
NSLog(@"%d", [s1 intValue]);
NSLog(@"%d", [s1 boolValue]);
NSLog(@"%f", [s1 floatValue]);
NSLog(@"%f", [s1 doubleValue]);

Mutable Strings

The NSMutableString class is a subclass of NSString. It offers you a way to work with strings whose contents can be modified. Once it is instantiated, you can append new contents to the string, allowing you to grow results before returning from a method. This example displays “Hello World. The results are in now.”

NSMutableString *myString = [NSMutableString stringWithString:
    @"Hello World. "];
[myString appendFormat:@"The results are %@ now.", @"in"];
NSLog(@"%@", myString);

Numbers and Dates

Foundation offers a large family of value classes. Among these are numbers and dates. Unlike standard C floats, integers, and so forth, these elements are all objects. They can be allocated and released as well as used in collections such as arrays, dictionaries, and sets. The following examples show numbers and dates in action, providing a basic overview of these classes.

Working with Numbers

The NSNumber class lets you treat numbers as objects. You can create new NSNumber instances using a variety of convenience methods, namely numberWithInt:, numberWithFloat:, numberWithBool:, and so forth. Once they are set, you extract those values via intValue, floatValue, boolValue, and so on, and use normal C-based math to perform your calculations.

You are not limited to extracting the same data type an object was set with. You can set a float and extract the integer value, for example. Numbers can also convert themselves into strings:

NSNumber *number = [NSNumber numberWithFloat:3.141592];
NSLog(@"%d", [number intValue]);
NSLog(@"%@", [number stringValue]);

One of the biggest reasons for using NSNumber objects rather than ints, floats, and so forth, is that they are objects. You can use them with Cocoa routines and classes. For example, you cannot set a user default (that is, a preference value) to, say, the integer 23, as in “You have used this program 23 times.” You can, however, store an object [NSNumber numberWithInt:23] and later recover the integer value from that object to produce the same user message.

If, for some reason, you must stick with C-style variables or byte arrays, consider using NSValue. The NSValue class allows you to encapsulate C data, including int, float, char, structures, and pointers into an Objective-C wrapper.

Working with Dates

As with standard C and time(), NSDate objects use the number of seconds since an epoch, which is a standardized universal time reference, to represent the current date. The iOS SDK epoch was at midnight on January 1, 2001. The standard UNIX epoch took place at midnight on January 1, 1970.

Each NSTimeInterval represents a span of time in seconds, stored with subsecond floating-point precision. The following code shows how to create a new date object using the current time and how to use an interval to reference some time in the future (or past):

// current time
NSDate *date = [NSDate date];

// time 10 seconds from now
date = [NSDate dateWithTimeIntervalSinceNow:10.0f];

You can compare dates by setting or checking the time interval between them. This snippet forces the application to sleep until 5 seconds into the future and then compares the date to the one stored in date:

// Sleep 5 seconds and check the time interval
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0f]];
NSLog(@"Slept %f seconds", [[NSDate date] timeIntervalSinceDate:date]);

The standard description method for dates returns a somewhat human-readable string, showing the current date and time:

// Show the date
NSLog(@"%@" [date description]);

To convert dates into fully formatted strings rather than just using the default description, use an instance of NSDateFormatter. You specify the format (for example, YY for two-digit years, and YYYY for four-digit years) using the object’s date format property. A full list of format specifiers is offered in the built-in Xcode documentation. In addition to producing formatted output, this class can also be used to read preformatted dates from strings, although that is left as an exercise for the reader.

// Produce a formatted string representing the current date
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]
    autorelease];
formatter.dateFormat = @"MM/dd/YY HH:mm:ss";
NSString *timestamp = [formatter stringFromDate:[NSDate date]];
NSLog(@"%@", timestamp);

Timers

When working with time, you may need to request that some action occur in the future. Cocoa offers an easy-to-use timer that triggers at an interval you specify; use the NSTimer class. The timer shown here triggers after 1 second and repeats until the timer is disabled:

[NSTimer scheduledTimerWithTimeInterval: 1.0f target: self
    selector: @selector(handleTimer:) userInfo: nil repeats: YES];

Each time the timer activates, it calls its target sending the selector message it was initialized with. The callback method takes one argument (notice the single colon), which is the timer itself. To disable a timer, send it the invalidate message; this releases the timer object and removes it from the current run loop.

- (void) handleTimer: (NSTimer *) timer
{
    printf("Timer count: %d\n", count++);
    if (count > 3)
    {
        [timer invalidate];
        printf("Timer disabled\n");
    }
}

Recovering Information from Index Paths

The NSIndexPath class is used with iOS tables. It stores the section and row number for a user selection—that is, when a user taps on the table. When provided with index paths, you can recover these numbers via the myIndexPath.row and myIndexPath.section properties. Learn more about this class and its use in Chapter 11.

Collections

The iOS SDK primarily uses three kinds of collections: arrays, dictionaries, and sets. Arrays act like C arrays. They provide an indexed list of objects, which you can recover by specifying which index to look at. Dictionaries, in contrast, store values that you can look up by keys. For example, you might store a dictionary of ages, where Dad’s age is the NSNumber 57 and a child’s age is the NSNumber 15. Sets offer an unordered group of objects and are usually used in the iOS SDK in connection with recovering user touches from the screen. Each of these classes offers regular and mutable versions, just as the NSString class does.

Building and Accessing Arrays

Create arrays using the arrayWithObjects: convenience method, which returns an autoreleased array. When calling this method, list any objects you want added to the array and finish the list with nil. (If you do not include nil in your list, you’ll experience a runtime crash.) You can add any kind of object to an array, including other arrays and dictionaries. This example showcases the creation of a three-item array:

NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];

The count property returns the number of objects in an array. Arrays are indexed starting with 0, up to one less than the count. Attempting to access [array objectAtIndex:array.count] causes an “index beyond bounds” exception and crashes. So always use care when retrieving objects, making sure not to cross either the upper or lower boundary for the array.

NSLog(@"%d", array.count);
NSLog(@"%@", [array objectAtIndex:0]);

Mutable arrays are editable. The mutable form of NSArray is NSMutableArray. With mutable arrays, you can add and remove objects at will. This snippet copies the previous array into a new mutable one and then edits the array by adding one object and removing another one. This returns an array of [@"One", @"Two", @"Four].

NSMutableArray *marray = [NSMutableArray arrayWithArray:array];
[marray addObject:@"Four"];
[marray removeObjectAtIndex:2];
NSLog(@"%@", marray);

Whether or not you’re working with mutable arrays, you can always combine arrays to form a new version containing the components from each. No checks are done about duplicates. This code produces a six-item array, including one, two, and three from the original array, and one, two, and four from the mutable array:

NSLog(@"%@", [array arrayByAddingObjectsFromArray:marray]);

Checking Arrays

You can test whether an array contains an object and recover the index of a given object. This code searches for the first occurrence of “Four” and returns the index for that object. The test in the if statement ensures that at least one occurrence exists:

if ([marray containsObject:@"Four"])
      NSLog(@"The index is %d",
        [marray indexOfObject:@"Four"]);

Converting Arrays into Strings

As with other objects, sending a description to an array returns an NSString that describes an array. In addition, you can use componentsJoinedByString to transform an NSArray into a string. The following code returns @"One Two Three":

NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSLog(@"%@", [array componentsJoinedByString:@" "]);

Building and Accessing Dictionaries

NSDictionary objects store keys and values, enabling you to look up objects using strings. The mutable version of dictionaries, NSMutableDictionary, lets you modify these dictionaries by adding and removing elements on demand. In iOS programming, you use the mutable class more often the static one, so these examples showcase mutable versions.

Creating Dictionaries

Use the dictionary convenience method to create a new mutable dictionary, as shown here. This returns a new initialized dictionary that you can start to edit. Populate the dictionary using setObject:forKey:.

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"1" forKey:@"A"];
[dict setObject:@"2" forKey:@"B"];
[dict setObject:@"3" forKey:@"C"];
NSLog(@"%@", [dict description]);
Searching Dictionaries

Searching the dictionary means querying the dictionary by key name. Use objectForKey: to find the object that matches a given key. When a key is not found, the dictionary returns nil. This returns @"1" and nil:

NSLog(@"%@", [dict objectForKey:@"A"]);
NSLog(@"%@", [dict objectForKey:@"F"]);
Replacing Objects

When you set a new object for the same key, Cocoa replaces the original object in the dictionary. This code replaces "3" with "foo" for the key "C":

[dict setObject:@"foo" forKey:@"C"];
NSLog(@"%@", [dict objectForKey:@"C"]);
Removing Objects

You can also remove objects from dictionaries. This snippet removes the object associated with the "B" key. Once removed, both the key and the object no longer appear in the dictionary.

[dict removeObjectForKey:@"B"];
Listing Keys

Dictionaries can report the number of entries they store plus they can provide an array of all the keys currently in use. This key list lets you know what keys have already been used. It lets you test against the list before adding an item to the dictionary, avoiding overwriting an existing key/object pair.

NSLog(@"The dictionary has %d objects", [dict count]);
NSLog(@"%@", [dict allKeys]);

Accessing Set Objects

Sets store unordered collections of objects. You encounter sets when working with the iPhone device family’s multitouch screen. The UIView class receives finger movement updates that deliver touches as an NSSet. To work with touches, you typically issue allObjects and work with the array that gets returned. Once converted, use standard array calls to list, query, and iterate through the touches. You can also use fast enumeration directly with sets.

Memory Management with Collections

Arrays, sets, and dictionaries automatically retain objects when they are added and release those objects when they are removed from the collection. Releases are also sent when the collection is deallocated. Collections do not copy objects. Instead, they rely on retain counts to hold onto objects and use them as needed.

Writing Out Collections to File

Both arrays and dictionaries can store themselves into files using writeToFile:atomically: methods so long as the types within the collections belong to the set of NSData, NSDate, NSNumber, NSString, NSArray, and NSDictionary. Pass the path as the first argument and a Boolean as the second. As when saving strings, the second argument determines whether the file is first stored to a temporary auxiliary and then renamed. The method returns a Boolean value: YES if the file was saved, NO if not. Storing arrays and dictionaries create standard property lists files.

NSString *path = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents/ArraySample.txt"];
if ([array writeToFile:path atomically:YES])
    NSLog(@"File was written successfully");

To recover an array or dictionary from file, use the convenience methods arrayWithContentsOfFile: and dictionaryWithContentsOfFile:. If the methods return nil, the file could not be read.

NSArray *newArray = [NSArray arrayWithContentsOfFile:path];
NSLog(@"%@", newArray);

Building URLs

NSURL objects point to resources. These resources can refer to both local files and to URLs on the Web. Create url objects by passing a string to class convenience functions. Separate functions have been set up to interpret each kind of URL. Once built, however, NSURL objects are interchangeable. Cocoa does not care if the resource is local or points to an object only available via the Net. This code demonstrates building URLs of each type, path and Web:

NSString *path = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents/foo.txt"];
NSURL *url1 = [NSURL fileURLWithPath:path];
NSLog(@"%@", url1);

NSString *urlpath = @"http://ericasadun.com";
NSURL *url2 = [NSURL URLWithString:urlpath];
NSLog(@"%d characters read",
    [[NSString stringWithContentsOfURL:url2] length]);

Working with NSData

If NSString objects are analogous to zero-terminated C strings, then NSData objects correspond to buffers. NSData provides data objects that store and manage bytes. Often, you fill NSData with the contents of a file or URL. The data returned can report its length, letting you know how many bytes were retrieved. This snippet retrieves the contents of a URL and prints the number of bytes that were read:

NSData *data = [NSData dataWithContentsOfURL:url2];
NSLog(@"%d", [data length]);

To access the core byte buffer that underlies an NSData object, use bytes. This returns a (const void *) pointer to actual data.

As with many other Cocoa objects, you can use the standard NSData version of the class or its mutable child, NSMutableData. Most Cocoa programs that access the Web, particularly those that perform asynchronous downloads, pull in a bit of data at a time. For those cases, NSMutableData objects prove useful. You can keep growing mutable data by issuing appendData: to add the new information as it is received.

File Management

The iOS SDK’s file manager is a singleton provided by the NSFileManager class. It can list the contents of folders to determine what files are found and perform basic file system tasks. The following snippet retrieves a file list from two folders. First, it looks in the sandbox’s Documents folder and then inside the application bundle itself.

NSFileManager *fm = [NSFileManager defaultManager];

// List the files in the sandbox Documents folder
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSLog(@"%@",[fm directoryContentsAtPath:path]);
// List the files in the application bundle
path = [[NSBundle mainBundle] bundlePath];
NSLog(@"%@",[fm directoryContentsAtPath:path]);

Note the use here of NSBundle. It lets you find the application bundle and pass its path to the file manager. You can also use NSBundle to retrieve the path for any item included in your app bundle. (You cannot, however, write to the application bundle at any time.) This code returns the path to the application’s Default.png image. Note that the file and extension names are separated and that each is case sensitive.

NSBundle *mb = [NSBundle mainBundle];
NSLog(@"%@", [mb pathForResource:@"Default" ofType:@"png"]);

The file manager offers a full suite of file-specific management. It can move, copy, and remove files as well as query the system for file traits and ownership. Here are some examples of the simpler routines you may use in your applications:

// Create a file
NSString *docspath = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents"];
NSString *filepath = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents/testfile"];
NSArray *array = [@"One Two Three" componentsSeparatedByString:@" "];
[array writeToFile:filepath atomically:YES];
NSLog(@"%@", [fm directoryContentsAtPath:docspath]);

// Copy the file
NSString *copypath = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents/copied"];
if (![fm copyItemAtPath:filepath toPath:copypath error:&error])
{
    NSLog(@"Copy Error: %@", [error localizedDescription]);
    return;
}
NSLog(@"%@", [fm directoryContentsAtPathdocspath]);

// Move the file
NSString *newpath = [NSHomeDirectory()
    stringByAppendingPathComponent:@"Documents/renamed"];
if (![fm moveItemAtPath:filepath toPath:newpath error:&error])
{
    NSLog(@"Move Error: %@", [error localizedDescription]);
    return;
}
NSLog(@"%@", [fm directoryContentsAtPath:docspath]);

// Remove a file
if (![fm removeItemAtPath:copypath error:&error])
{
    NSLog(@"Remove Error: %@", [error localizedDescription]);
    return;
}
NSLog(@"%@", [fm directoryContentsAtPath:docspath]);
  • + Share This
  • 🔖 Save To Your Account