fileExistsAtPath为存在的目录返回NO

Gru*_*kes 6 objective-c ios

fileExistsAtPath对于存在的目录,返回NO.如果我有以下代码:

NSURL *newDirectoryPath = ... // path does not begin with a tilda
                              // and is created using URLByAppendingPathComponent:isDirectory:

BOOL directoryExists = [self.fileManager fileExistsAtPath:[newDirectoryPath absoluteString]];
if (NO == directoryExists)
{
    BOOL ret = [self.fileManager moveItemAtURL:self.currentPresentationDirectoryPath toURL:newDirectoryPath error: &err];
    // ret is YES, err is nil

    directoryExists = [self.fileManager fileExistsAtPath:[newDirectoryPath absoluteString]];
}
Run Code Online (Sandbox Code Playgroud)

即使目录刚刚成功创建moveItemAtURL,fileExistsAtPath仍然返回NO.

我知道文档说这个:

建议不要尝试基于文件系统的当前状态或文件系统上的特定文件来预测行为.在文件系统竞争条件下,这样做会导致奇怪的行为.

但我想了解这里的问题 - 如果我关闭应用程序并重新启动它,那么fileExistsAtPath上面代码中的第一次检查仍然返回NO,即使该代码先前已在代码的先前执行期间成功创建,并且我可以在管理器中看到该目录,我也可以成功地从目录的内容中读取等.

PS有没有fileExistsAtURL:方法?

v1A*_*xvw 20

如果您有NSURL,-absoluteURL则不会返回可用路径NSFileManager.它将返回带有file://前缀的绝对URL .例如:file:///path/to/file.

而是尝试使用其他方法,例如-path.检查是否有效.

NSURL *myURL = /* some url */;
NSString *myPath;
BOOL exi;

myPath = [myURL path];
exi = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if(!exi) {
    NSLog(@"File does not exist");
}
Run Code Online (Sandbox Code Playgroud)