The NSFileManager createDirectoryAtPath method returns a false result on iOS

When I try to create a folder using the code below, it returns NO with an error when I try to create a folder that already exists, instead of returning YES:

[[NSFileManager defaultManager] createDirectoryAtPath:[documentsPath stringByAppendingPathComponent:@"temp"] withIntermediateDirectories:NO attributes:nil error:&error]; 

Apple documentation says:

 Return Value YES if the directory was created or already exists or NO if an error occurred. 

So, I have to get YES for success or if the folder exists. But I get this message when a folder exists:

 Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn't be completed. (Cocoa error 516.)" UserInfo=0x200ef5f0 {NSFilePath=/var/mobile/Applications/DA657A0E-785D-49B4-9258-DF9EBAC5D52A/Documents/temp, NSUnderlyingError=0x200ef590 "The operation couldn't be completed. File exists"} 

Is this a mistake and should Apple report it, or am I something wrong?

+4
source share
2 answers

[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:] will fail if the file exists and it is not a directory.

Thus, the way forward is to not bother creating the directory if it already exists, and throw an exception if it exists, and is not a directory:

 NSString *filename = [documentsPath stringByAppendingPathComponent:@"temp"]; NSFileManager *fileman = [NSFileManager defaultManager]; BOOL isDir = NO; if (![fileman fileExistsAtPath:filename isDirectory:&isDir]) { // Create the directory } else if (!isDir) { NSLog(@"Cannot proceed!"); // Throw exception } 
+3
source

I think you need to use withIntermediateDirectories YES to get behavior in Apple docs.

0
source

All Articles