Ad

Our DNA is written in Swift
Jump

Getting Standard Paths

These are the standard methods of getting the app directory and the documents directory. Remember that on the iPhone the app as well as the documents directory are “sandboxed” i.e. each app has it’s own two directories.

Here’s how you can get the path for files in your app bundle/directory:

// a regular file
NSString *plistPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"File.plist"];
 
// this works also for localized files, gets the best matching localized variant
NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; // alternate method to get bundle
NSString *path = [thisBundle pathForResource:@"File" ofType:@"plist"];

One common mistake is to pass a file name including extension in the first parameter  of the pathForResource method. This won’t work, pass only the name without extension as first parameter and only the extension as second parameter.

And to get something from the documents directory you can do it like this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"File.plist"];

You’ll find yourself copy/pasting these lines all the time basically for every file that you are reading or writing.


Categories: Recipes

0 COmments »

Trackbacks

  1. Transfer App Data Back to Your Mac | Dr. Touch

Leave a Comment