O'Reilly logo

Programming iOS 4 by Matt Neuburg

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

Chapter 36. Persistent Storage

The device on which your app runs contains flash memory that functions as the equivalent of a hard disk, holding files that survive the device’s being powered down (persistent storage). Apps can store files to, and retrieve them from, this virtual hard disk. Apps can also define document types in which they specialize and can hand such documents to one another.

The Sandbox

The hard disk as a whole is not open to your app’s view. A limited portion of the hard disk is dedicated to your app alone: this is your app’s sandbox. The idea is that every app, seeing only its own sandbox, is hindered from spying or impinging on the files belonging to other apps. Your app can also see some higher-level directories owned by the system as a whole, but cannot write to them.

You can create directories (folders) within the sandbox. In addition, the sandbox contains some standard directories. For example, suppose you want a reference to the Documents directory. Here’s how to access it:

NSString* docs = [NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

That code returns a path string for the Documents directory. Starting in iOS 4, the preferred way to refer to a file or directory is with a URL. You obtain this from an NSFileManager instance:

NSFileManager* fm = [[NSFileManager alloc] init]; // ... NSError* err = nil; NSURL* docsurl = [fm URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES ...

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