【问题标题】:NSFileManager's method createDirectoryAtPath returns false result on iOSNSFileManager 的方法 createDirectoryAtPath 在 iOS 上返回错误结果
【发布时间】:2013-02-21 02:36:33
【问题描述】:

当我尝试使用下面的代码创建文件夹时,当我尝试创建一个已经存在的文件夹而不是返回 YES 时,它会返回 NO 并返回错误:

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

Apple 的 documentation 说:

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

所以我应该在成功或文件夹存在时得到“是”。但是当文件夹存在时我收到此消息:

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"}

这是一个错误,应该报告给 Apple 还是我做错了什么?

【问题讨论】:

  • @trojanfoe:我确定。我已经重新安装了应用程序。第一次创建“临时”文件夹,但所有后续尝试都给我错误。

标签: ios directory nsfilemanager create-directory


【解决方案1】:

如果文件存在且不是目录,[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:] 将失败。

所以前进的方向是如果目录已经存在就不要创建目录,如果它存在并且不是目录则抛出异常:

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
}

【讨论】:

  • 如果我对您的理解正确,那么 Apple 的文档或实施是否有误?
  • @BorutTomazin 是的,我想是的;听起来像一个错误,所以你需要解决它(我认为最好避免做一些无论如何都不需要做的事情)。
  • 好的。很高兴知道。我会向苹果报告错误。谢谢!
【解决方案2】:

我认为您需要使用 withIntermediateDirectories YES 来获取 Apple 文档中的行为。

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2011-06-22
    • 2016-04-22
    • 2023-03-21
    • 1970-01-01
    • 2012-07-12
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多