64

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?

Eric Galluzzo
  • 3,191
  • 1
  • 20
  • 20
bwinton
  • 1,978
  • 2
  • 19
  • 21

5 Answers5

97

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.

Matej
  • 9,548
  • 8
  • 49
  • 66
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 1
    Cool, that's what I'll use, but why it and not the other way? – bwinton Nov 07 '08 at 17:42
  • 3
    You can use the other way, but if an upgrade to the OS changes the default structure, this answer is guaranteed to still work with the new layout while the first way will either fail or start re-creating legacy directories. – Jason Coco Nov 07 '08 at 18:12
50

Here is the code that I use in my framework.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
Lee
  • 751
  • 5
  • 2
16

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

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first

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

An array of URL 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.

Zelko
  • 3,793
  • 3
  • 34
  • 40
  • 2
    That is right. Our knowledge should be upgraded that in iOS we should use NSURL, rather than NSString (for path) to represent local file. – Juguang May 07 '13 at 09:39
1

I use this

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

In swift v3, I used the following snippet

var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
Suresh Velusamy
  • 2,338
  • 19
  • 24