Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager - URLsForDirectory... or URLForDirectory

-[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] requires a single NSSearchPathDomainMask and returns a single URL. (The ...appropriateForURL:create:error: part is a bit confusing in documentation.)

-[NSFileManager URLsForDirectory:inDomains:] allows you to create a bit-mask for the domains parameter and returns an array of URLs.

It seems to me there is overlap between these two methods. If my goal is to get the Documents, or Library, or etc directory from an iOS app's sandbox, when should I use one over the other?

like image 992
edelaney05 Avatar asked Dec 21 '12 01:12

edelaney05


1 Answers

The standard way to get access to the Documents directory (or other similar directories) is code like the following:

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

This is similar to doing:

NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsURL = URLs[0];

The key difference is the first gives you the path as an NSString while the second gives you the path as an NSURL.

The other method can be used by doing:

NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

You can pass NO for the Documents directory because it always exists. You should pass YES for the application support directory since it doesn't exist by default. And ideally you should not pass in nil for the error so you can see what happened if the method call returns nil.

Any of these three approaches work. Use the 1st if you want the path as a string. Use the 3rd if you want it as a URL. Use the 2nd if you have the rare need to pass in more than one domain.

like image 131
rmaddy Avatar answered Nov 15 '22 11:11

rmaddy