I'm building an app which caches images in the Documents directory of the app bundle. In order to make sure the directories exist, I want to check to see if they exist and, if they don't, create them at the point at which the application starts.
Currently, I'm doing this in didFinishLaunchingWithOptions:
like so:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSArray *directoriesToCreate = [[NSArray alloc] initWithObjects:
@"DirA/DirA1",
@"DirA/DirA2",
@"DirB/DirB2",
@"DirB/DirB2",
@"DirC",
nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
for (NSString *directoryToCreate in directoriesToCreate) {
NSString *directoryPath = [documentsPath stringByAppendingPathComponent:directoryToCreate];
NSLog(directoryPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:YES]) {
NSError *directoryCreateError = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
withIntermediateDirectories:YES
attributes:nil
error:&directoryCreateError];
}
}
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
return YES;
}
On the very first run of the application – when none of the directories exist – the application runs, the directories are created as expected and everything runs just fine.
When the application is terminated, and runs again, I get an EXC_BAD_ACCESS signal on the fileExistsAtPath:
call on [NSFileManager defaultManager]
.
What I don't understand is why this runs just fine when the directories don't exist, but it falls over when they do exist.
Can anyone offer any assistance?
You're using the check function in the wrong way. 2nd parameter must be a pointer to a boolean variable which will be filled after function is called:
You are using function like this:
[[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:YES];
But function should be used like this:
BOOL isDir;
[[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDir];
if (isDir) { // file exists and it is directory.
isDirectory is a (BOOL*) for returning a boolean describing if the path points at a directory. You are passing a BOOL.
The reason it doesn't crash if the directory exists is that the value isn't set if the directory doesn't exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With