gpt4 book ai didi

iphone - 使用 NSFileManager createDirectoryAtPath 返回值不正确 :

转载 作者:搜寻专家 更新时间:2023-10-30 19:40:47 26 4
gpt4 key购买 nike

我正在为现有的 iPhone 应用程序开发一项新功能,并想在该应用程序的本地“文档”文件夹中创建几个新目录。我已经使用推荐的方法成功完成了此操作:

[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:]

在阅读此方法的文档时,我对苹果官方 documentation 中列出的返回值很感兴趣。 :

Return Value: YES if the operation was successful or already exists, otherwise NO

每次我的应用程序启动时,我都想确保目录正确就位。我认为一个聪明的方法是在每次启动时调用 createDirectory: 方法并利用该方法的返回值。如果由于某种原因该目录丢失,则会创建它。如果目录已经存在,返回值仍为YES。然后可以将 NO 返回值用作附加恢复/修复逻辑的标志。

不幸的是,我得到的结果似乎与 Apple 的文档不一致。如果目录已经存在,该方法将返回 NO - 当 Apple 的文档说在这种情况下它应该返回 YES 时。

下面的程序演示了这种行为:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSFileManager * fm = [NSFileManager defaultManager];
bool testDirectoryCreated = NO;

testDirectoryCreated = [[NSFileManager defaultManager]createDirectoryAtPath: [NSString stringWithFormat:@"%@/%@",[fm currentDirectoryPath],@"TestDirectory"]
withIntermediateDirectories: NO
attributes: nil
error: NULL];

NSLog(@"TestDirectory Created: %@\n", (testDirectoryCreated ? @"YES" : @"NO"));

testDirectoryCreated = [[NSFileManager defaultManager]createDirectoryAtPath: [NSString stringWithFormat:@"%@/%@",[fm currentDirectoryPath],@"TestDirectory"]
withIntermediateDirectories: NO
attributes: nil
error: NULL];

NSLog(@"TestDirectory Created: %@\n", (testDirectoryCreated ? @"YES" : @"NO"));

[pool drain];

return 0;

当程序执行时,它会在第一次调用 createDirectory: 时打印 YES,在第二次调用时打印 NO - 当“TestDirectory”已经存在时。

这是 Apple 文档中的错误,还是我遗漏了什么?

此外,还有其他任何仅用于验证我的目录结构完整性的想法吗?有没有我可以调用的简单的“目录存在”方法?

谢谢,

汤姆

最佳答案

如果您还想通过此方法方便地检查目录是否存在,则必须将 TRUE 传递给 withIntermediateDirectories: 参数。

Apple 的文档中有说明

In addition, if you pass NO for this parameter, the directory must not exist at the time this call is made.

关于iphone - 使用 NSFileManager createDirectoryAtPath 返回值不正确 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3337617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com