I keep forgetting this time and time again. There is more than one way to slice a cake:
Option 1
This is how the Apple Templates with Core Data do it. This method takes a file name and returns its URL in the Documents Directory:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
- (NSURL*)grabFileURL:(NSString *)fileName { // find Documents directory NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; // append a file name to it documentsURL = [documentsURL URLByAppendingPathComponent:fileName]; return documentsURL; } // if you need the path instead NSString *documentsPath = [documentsURL path]; |
Option 2
Here we make use of the foundation function NSHomeDirectory. This method takes a file name and returns its path in the Documents Directory:
1 2 3 4 5 6 7 8 9 10 |
- (NSString *)grabFilePath:(NSString *)fileName { NSString *filePath = [[NSString alloc]initWithFormat:@"Documents/%@", fileName]; NSString *documentsFilePath = [NSHomeDirectory()stringByAppendingPathComponent:filePath]; return documentsFilePath; } // and to convert that back into a URL: NSURL *documentsURL = [NSURL fileURLWithPath:documentsFilePath]; |
Related
If you don’t need to persist files you can make use of the NSTemporaryDirectory. Those files are not backed up and may be cleared by the OS when space is needed. It’s still good practice to delete them yourself if your app no longer needs them here.