Ios NSData:writeToFile返回错误“;文件不存在';“不存在”;
我目前正在使用以下代码在documents文件夹的子文件夹中写入NSDataIos NSData:writeToFile返回错误“;文件不存在';“不存在”;,ios,objective-c,Ios,Objective C,我目前正在使用以下代码在documents文件夹的子文件夹中写入NSData NSData* dataToSave=...; NSFileManager* fileManager = [NSFileManager defaultManager]; NSString* documentsDir=[ NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtInde
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;
}
它一直在工作,直到我在“发布模式”中测试这个配置。NSData:writeToFile开始返回否
,错误为:文件“myfile.jpeg”不存在
问题在哪里
谢谢谢谢@mbi,我找到了答案 问题在于验证父文件夹是否存在时:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]&&!isDir)
这是不正确的。由于isDirectory参数不安全,isDir
即使方法的结果为NO
,也可以为真。因此,正确的评估方法是:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:nil])
或者,如果要处理文件存在但不是目录的情况:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]){
...
}else if(!isDir) {
...
}
试试这个方法
if (![dataToSave writeToFile:desiredFile atomically:YES])
{
NSLog(@"Error writing to file : %@",desiredFile);
return NO;
}
你的意思是
“/mfile.jpeg”
不是myfile.jpeg?当你追加字符串时,你应该使用@”/“
,但是你使用的是stringByAppendingPathComponent
传递文件名,不是slashIt是一个抄本错误,我使用的是没有“/”的版本,已将问题更新为您声明和分配desiredFile
,但随后可能使用未声明的itemImagePath
?如果(![fileManager fileExistsAtPath:desiredFolder isDirectory:&dirExist]&&!dirExist),则条件可能有问题。对我来说,你的代码似乎有点过于小心了。只需使用[fileManager createDirectoryAtPath:DesiredFolderwithIntermediateDirectory:YES attributes:nil error:nil]
然后[DataToSaveWriteToFile:itemImagePath选项:NSDataWritingAtomic error:&error]
我认为这是正确的,但是我不同意当方法返回NO
时,isDir
可以是YES
。假设您将isDir
初始化为no
,则这没有任何意义。不存在的文件也不能是目录。