Warm tip: This article is reproduced from stackoverflow.com, please click
ios nsdocumentdirectory

What is the documents directory (NSDocumentDirectory)?

发布于 2020-03-27 15:45:03

Can someone explain to me what the documents directory is on an iOS app and when to use it?

Here is what I believe at present:

To me, it seems to be a central folder where the user can store any files needed for the app.

This would be a different location than where Core Data stores its data?

It seems like each app gets its own documents directory.

I am free to create a subdirectory of the documents directory, like documents directory/images, or documents directory/videos?

Questioner
user798719
Viewed
17
1,582 2016-08-11 09:20

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]