O'Reilly logo

iOS App Development Portable Genius by Richard Wentk

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Files

The easiest way to save and load data is to use the methods built into the data collection objects—NSArray, NSDictionary, NSSet, NSString, and so on. The easy way to save other objects is to add them to an array and save the array.

note_2c.eps

Plain C types must be wrapped inside an NSValue object first. For details, see Chapter 7.

caution_exclamation_2c.eps

This option works for objects that support NSCoder—the system iOS uses to convert objects into save-able and load-able binary. If an object doesn’t support NSCoder, you have to add appropriate encoding and decoding methods yourself. (In this context “encoding” and “decoding” mean “converting to and from binary.”) You can find detailed tutorials online, and also in Cocoa in Wiley’s Developer Reference series.

To save an array, use the writeToFile:atomically: method, like this:

[anArray writeToFile: pathString atomically: YES];

Saving atomically guarantees the file is saved correctly. If there isn’t enough disk space, the method returns a BOOL as anerror code.

To read an array, use the arrayWithContentsOfFile: method, like this:

NSArray *arrayReloaded = [NSArray arrayWithContentsOfFile: pathString];

How do you create the pathString? iOS uses a limited “sandboxed” filing system, so apps can save files only in very limited locations in a protected ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required