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, and in turn is protected from having its own files spied or impinged on by other apps. Your app’s sandbox is thus a safe place for you to store your data. Your sandbox, and hence your data, will be deleted if the user deletes your app; otherwise, it should reliably persist. (Your app can also see some higher-level directories owned by the system as a whole, but cannot write to them.)
The sandbox contains some standard directories. For example, suppose you want a reference to the Documents directory. Here’s one way to access it:
NSString* docs = [NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES) lastObject];That code returns a path string for the Documents directory. The preferred way to refer to a file or directory, however, is with a URL. You can obtain this from an NSFileManager instance:
NSFileManager* fm = [NSFileManager new];
NSError* err = nil;
NSURL* docsurl =
[fm URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask appropriateForURL:nil
create:YES error:&err];
// error-checking omittedA question that will immediately occur to you is: where should I put files and folders that I want to save now and read later? The Documents directory can be a good ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access