What's the best way to find the user's Doc

2020-01-24 06:37发布

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

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

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

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

NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);

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

5条回答
时光不老,我们不散
2楼-- · 2020-01-24 07:21

In swift v3, I used the following snippet

var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
查看更多
老娘就宠你
3楼-- · 2020-01-24 07:25

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.

查看更多
聊天终结者
4楼-- · 2020-01-24 07:28

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

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.

查看更多
\"骚年 ilove
5楼-- · 2020-01-24 07:33

Here is the code that I use in my framework.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
查看更多
做个烂人
6楼-- · 2020-01-24 07:39

I use this

NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *zipLocalPath = [documentPath stringByAppendingString:fileName];
查看更多
登录 后发表回答