Reputation: 32253
I'm currently using the following code to write a NSData in a subfolder of the documents folder.
NSData* dataToSave=...;
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* documentsDir=[
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
objectAtIndex:0];
NSString* desiredFolder=[documentsDir stringByAppendingPathComponent:@"MySubfolder"];
BOOL isDir;
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]&&!isDir)
{
NSError* error;
[fileManager createDirectoryAtPath:desiredFolder
withIntermediateDirectories:NO attributes:nil error:&error];
if (error) {
NSLog(@"Error%@", error.localizedDescription);
}
}
NSString* desiredFile=[desiredFolder stringByAppendingPathComponent:@"mfile.jpeg"];
if (![dataToSave writeToFile:desiredFile options:NSDataWritingAtomic error:&error])
{
NSLog(@"Error %@",error.localizedDescription);
return NO;
}
It was working until I tested this config in "release mode" . There the NSData:writeToFile started to return NO
, with the error: The file 'myfile.jpeg´ doesn't exist
.
Where is the problem?
Thanks
Upvotes: 1
Views: 2036
Reputation: 801
Try this method.
if (![dataToSave writeToFile:desiredFile atomically:YES])
{
NSLog(@"Error writing to file : %@",desiredFile);
return NO;
}
Upvotes: 0
Reputation: 32253
Thanks to @mbi I found the answer.
The problem is when validating the existence of the parent folder:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]&&!isDir)
This is incorrect. Since the isDirectory param is unsafe isDir
can be true even if the result of the method is NO
. So the correct way to evaluate is just:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:nil])
Or if you want to handle the case where the file exists but is not a directory:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]){
...
}else if(!isDir) {
...
}
Upvotes: 1