什么是文档目录(NSDocumentDirectory)?

有人可以向我解释什么文件目录是在iOS应用程序和何时使用它?

这是我现在所相信的:

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

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

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

我可以自由创build文件目录的子目录,如文件目录/图像,或文件目录/video?

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

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

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

iOS 8和更新,这是推荐的方法

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

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

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

文档目录允许您存储您的应用创build或可能需要的文件和子目录。

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

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

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

苹果认可的方式(从上面的链接)如下:

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

我无法find被接受的答案build议的文档中的代码,但我发现在这里更新的等价物:

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

 - (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; } 

它不鼓励使用NSSearchPathForDirectoriesInDomain:

NSSearchPathForDirectoriesInDomains函数的行为与URLsForDirectory:inDomains:方法相似,但是将目录的位置作为基于string的path返回。 您应该使用URLsForDirectory: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 

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

这个代码在Swift 2.1中适用于我

 func getDocsDir() -> NSURL? { let fm = NSFileManager.defaultManager() return fm.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last } 

Swift 3和4作为全球变种:

 var documentsDirectoryUrl: URL { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! } 

除了Documents文件夹,iOS还允许您将文件保存到temp文件夹和Library文件夹。

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

  • “你应该把你的应用程序的文件的位置”

你可以使用这个代码访问文件目录,它基本上用于以plist格式存储文件:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; return documentsDirectory; 

这里有一个有用的小函数,这使得使用/创buildiOS文件夹更容易一些。

您将它传递给子文件夹的名称,它会将完整的path返回给您,并确保该目录存在。

(就我个人而言,我将这个静态函数放在我的AppDelete类中,但也许这不是最聪明的地方。)

以下是您将如何调用它以获取MySavedImages子目录的“完整path”:

 NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"]; 

这里是完整的function:

 +(NSString*)getFullPath:(NSString*)folderName { // Check whether a subdirectory exists in our sandboxed Documents directory. // Returns the full path of the directory. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); if (paths.count < 1) return nil; NSString *rootFolder = [paths firstObject]; NSString* fullFolderPath = [rootFolder stringByAppendingPathComponent:folderName]; BOOL isDirectory; NSFileManager* manager = [NSFileManager defaultManager]; if (![manager fileExistsAtPath:fullFolderPath isDirectory:&isDirectory] || !isDirectory) { NSError *error = nil; NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey]; [manager createDirectoryAtPath:fullFolderPath withIntermediateDirectories:YES attributes:attr error:&error]; if (error) { NSLog(@"Error creating directory path: %@", [error localizedDescription]); return nil; } } return fullFolderPath; } 

使用这个小函数,很容易在你的应用程序的Documents目录下创build一个目录(如果它还不存在的话),并写入一个文件。

以下是我将如何创build目录,并将其中一个图像文件的内容写入其中:

 // Let's create a "MySavedImages" subdirectory (if it doesn't already exist) NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"]; // As an example, let's load the data in one of my images files NSString* imageFilename = @"icnCross.png"; UIImage* image = [UIImage imageNamed:imageFilename]; NSData *imageData = UIImagePNGRepresentation(image); // Obtain the full path+filename where we can write this .png to, in our new MySavedImages directory NSString* imageFilePathname = [fullPath stringByAppendingPathComponent:imageFilename]; // Write the data [imageData writeToFile:imageFilePathname atomically:YES]; 

希望这可以帮助 !