I created a Utilities singleton to keep things I refer to often. These are the methods I use for referring to directories.
#pragma mark - Application's Documents directory
// Directory locations
+ (NSString *)applicationCachesDirectory {
return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}
+ (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
+ (NSString *)applicationLibraryDirectory {
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
}
Here’s one for retrieving the contents of a file stored in the Caches Directory. Notice how it uses [self applicationCachesDirectory] to get the location of the directory.
// Cached files for results
+ (NSString *)cachedFilePath:(NSString *)fileName {
NSString *pathComponent = [NSString stringWithFormat:@"%@.txt",fileName];
NSString *filePath = [[self applicationCachesDirectory] stringByAppendingPathComponent:pathComponent];
return filePath;
}
If I want to store the results in the Documents directory, I’ll use this to construct the path.
NSString *resultsFilePath = [ [Utilities applicationDocumentsDirectory] stringByAppendingPathComponent:[self formattedHTMLFileName:@"Results"] ];
Here’s a slightly more complicated example where I retrieve the contents of a cached file. Note that it makes use of cachedFilePath:fileName as described above.
+ (NSString *)cachedFileContents:(NSString *)fileName {
NSStringEncoding encoding; NSError* error = nil;
NSString *text = [NSString stringWithContentsOfFile:[self cachedFilePath:fileName] usedEncoding:&encoding error:&error];
return text;
}
Here’s another example. This time I’m loading a string with the contents of the FullResults file.
NSStringEncoding encoding;
NSError* error = nil;
NSString *resultsText = [NSString stringWithContentsOfFile:[Utilities cachedFilePath:@"FullResults"] usedEncoding:&encoding error:&error];