什么是文件目录(NSDocumentDirectory)?

use*_*719 121 ios nsdocumentdirectory

有人可以向我解释iOS应用程序上的文档目录以及何时使用它?

以下是我目前的看法:

对我来说,它似乎是一个中央文件夹,用户可以存储该应用程序所需的任何文件.

这与Core Data存储数据的位置不同?

似乎每个应用程序都有自己的文档目录.

我可以自由创建文件目录的子目录,如文件目录/图像,或文件目录/视频?

Wri*_*sCS 193

您的应用程序(在非越狱设备上)在"沙盒"环境中运行.这意味着它只能访问自己内容中的文件和目录.例如文档.

请参阅iOS应用程序编程指南.

要访问应用程序沙箱的Documents目录,可以使用以下命令:

iOS 8及更新版本,这是推荐的方法

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

如果您需要支持iOS 7或更早版本

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

文档目录允许您存储应用程序创建或可能需要的文件和子目录.

要访问应用程序沙箱的目录中的文件,请使用(代替paths上述):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]
Run Code Online (Sandbox Code Playgroud)

  • 我不会在@"〜/ Documents"中使用这种方法.硬编码路径绝不是一个好主意.它现在可以工作,但如果Apple选择重命名或移动Documents目录,您的应用程序将会中断.`NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);`将始终为您提供正确的目录! (35认同)
  • 每次我必须使用它时,我需要谷歌这个搞笑.我认为所有移动平台都应该为home/writable目录提供默认的全局参数 (20认同)
  • 您仍应使用提供的API.这就是为什么它在那里!你到现在为止都很幸运. (16认同)
  • 我发现[@"〜/ Documents"stringByExpandingTildeInPath]做同样的事情.有什么理由不鼓励这样做吗? (13认同)

liv*_*ech 41

在iOS 8中已更改.请参阅以下技术说明:https://developer.apple.com/library/ios/technotes/tn2406/_index.html

Apple批准的方式(来自上面的链接)如下:

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Run Code Online (Sandbox Code Playgroud)

  • **这就是你想要的答案!**这一年差不多是2016年了.这是一个流行的问题与过时的答案. (7认同)

Har*_*ngh 21

我无法在接受的答案建议的文档中找到代码,但我在此处找到了更新的等效内容:

文件系统编程指南::访问文件和目录»

- (NSURL*)applicationDataDirectory {
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                 inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;

    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }

    // If a valid app support directory exists, add the
    // app's bundle ID to it to specify the final directory.
    if (appSupportDir) {
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
    }

    return appDirectory;
}
Run Code Online (Sandbox Code Playgroud)

它不鼓励使用NSSearchPathForDirectoriesInDomain:

NSSearchPathForDirectoriesInDomains函数的行为类似于URLForDirectory:inDomains:方法,但将目录的位置作为基于字符串的路径返回.您应该使用URLForDirectory:inDomains:方法.

以下是一些其他有用的目录常量.毫无疑问,iOS中并不支持所有这些功能.您还可以使用NSHomeDirectory()函数:

在iOS中,主目录是应用程序的沙箱目录.在OS X中,它是应用程序的沙箱目录或当前用户的主目录(如果应用程序不在沙箱中)

来自NSPathUtilities.h

NSApplicationDirectory = 1,             // supported applications (Applications)
    NSDemoApplicationDirectory,             // unsupported applications, demonstration versions (Demos)
    NSDeveloperApplicationDirectory,        // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory.
    NSAdminApplicationDirectory,            // system and network administration applications (Administration)
    NSLibraryDirectory,                     // various documentation, support, and configuration files, resources (Library)
    NSDeveloperDirectory,                   // developer resources (Developer) DEPRECATED - there is no one single Developer directory.
    NSUserDirectory,                        // user home directories (Users)
    NSDocumentationDirectory,               // documentation (Documentation)
    NSDocumentDirectory,                    // documents (Documents)
    NSCoreServiceDirectory,                 // location of CoreServices directory (System/Library/CoreServices)
    NSAutosavedInformationDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 11,   // location of autosaved documents (Documents/Autosaved)
    NSDesktopDirectory = 12,                // location of user's desktop
    NSCachesDirectory = 13,                 // location of discardable cache files (Library/Caches)
    NSApplicationSupportDirectory = 14,     // location of application support files (plug-ins, etc) (Library/Application Support)
    NSDownloadsDirectory NS_ENUM_AVAILABLE(10_5, 2_0) = 15,              // location of the user's "Downloads" directory
    NSInputMethodsDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 16,           // input methods (Library/Input Methods)
    NSMoviesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 17,                 // location of user's Movies directory (~/Movies)
    NSMusicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 18,                  // location of user's Music directory (~/Music)
    NSPicturesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 19,               // location of user's Pictures directory (~/Pictures)
    NSPrinterDescriptionDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 20,     // location of system's PPDs directory (Library/Printers/PPDs)
    NSSharedPublicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 21,           // location of user's Public sharing directory (~/Public)
    NSPreferencePanesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 22,        // location of the PreferencePanes directory for use with System Preferences (Library/PreferencePanes)
    NSApplicationScriptsDirectory NS_ENUM_AVAILABLE(10_8, NA) = 23,      // location of the user scripts folder for the calling application (~/Library/Application Scripts/code-signing-id)
    NSItemReplacementDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 99,       // For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
    NSAllApplicationsDirectory = 100,       // all directories where applications can occur
    NSAllLibrariesDirectory = 101,          // all directories where resources can occur
    NSTrashDirectory NS_ENUM_AVAILABLE(10_8, NA) = 102                   // location of Trash directory
Run Code Online (Sandbox Code Playgroud)

最后,NSURL类别中的一些便捷方法 http://club15cc.com/code/ios/easy-ios-file-directory-paths-with-this-handy-nsurl-category


Ant*_*ich 8

Swift 3和4作为全局变量:

var documentsDirectory: URL {
    return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}
Run Code Online (Sandbox Code Playgroud)

作为FileManager扩展:

extension FileManager {
    static var documentsDirectory: URL {
        return `default`.urls(for: .documentDirectory, in: .userDomainMask).last!
    }

    var documentsDirectory: URL {
        return urls(for: .documentDirectory, in: .userDomainMask).last!
    }
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*son 6

为这种尴尬的调用添加一个扩展到FileManager可能更干净,如果没有别的话,整洁.就像是:

extension FileManager {
    static var documentDir : URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    }
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 5

除了该Documents文件夹,iOS还允许您将文件保存到tempLibrary文件夹.

有关使用哪一个的更多信息,请参阅文档中的以下链接: