ios 在 iPhone 上查找用户文档目录的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/272544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:22:19  来源:igfitidea点击:

What's the best way to find the user's Documents directory on an iPhone?

iosobjective-ciphonecocoa-touch

提问by bwinton

I'm reading Erica Sadun's iPhone Developer's Cookbook, and ran into a question.

我正在阅读 Erica Sadun 的iPhone Developer's Cookbook,并遇到了一个问题。

She says in the book that the way to find the user's Documents directory is with the code:

她在书中说,找到用户的Documents目录的方法是用代码:

[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

but that seems slightly brittle, and dissimiliar to the normal Mac way of doing it, which would be:

但这似乎有点脆弱,并且与正常的 Mac 方式不同,这将是:

NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);

Are there any particular reasons to use one over the other?

是否有任何特别的理由使用一个而不是另一个?

回答by Ben Gottlieb

Objc:

对象:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

Swift:

迅速:

var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

You'll want the first element of the returned array.

您需要返回数组的第一个元素。

回答by Lee

Here is the code that I use in my framework.

这是我在框架中使用的代码。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

回答by Zelko

You should consider using the NSFileManager methods which return URLs, which are the preferred format.

您应该考虑使用返回 URL 的 NSFileManager 方法,这是首选格式。

let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

This method is intended to locate known and common directories in the system.

此方法旨在定位系统中的已知和常见目录。

An array of NSURL objects identifying the requested directories. The directories are ordered according to the order of the domain mask constants, with items in the user domain first and items in the system domain last.

标识请求目录的 NSURL 对象数组。目录根据域掩码常量的顺序排序,用户域中的项目在前,系统域中的项目在后。

回答by Nguy?n V?n Chung

I use this

我用这个

NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *zipLocalPath = [documentPath stringByAppendingString:fileName];

回答by Suresh Velusamy

In swift v3, I used the following snippet

在 swift v3 中,我使用了以下代码段

var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)