简体   繁体   English

在iPhone上找到用户的Documents目录的最佳方法是什么?

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

I'm reading Erica Sadun's iPhone Developer's Cookbook , and ran into a question. 我正在阅读Erica Sadun的iPhone开发者手册 ,并遇到了一个问题。

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? 是否有任何特殊原因使用一个而不是另一个?

Objc: 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. 您将需要返回数组的第一个元素。

Here is the code that I use in my framework. 这是我在框架中使用的代码。

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

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. 标识所请求目录的NSURL对象数组。 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. 根据域掩码常量的顺序对目录进行排序,首先是用户域中的项目,最后是系统域中的项目。

I use this 我用这个

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM