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.
Plain C types must be wrapped inside an NSValue object first. For details, see Chapter 7.
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 ...