fileExistsAtPath对于存在的目录返回NO

6

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]];
}

尽管使用moveItemAtURL创建目录成功,但fileExistsAtPath仍然返回NO。虽然文档上说“不建议基于文件系统或特定文件的当前状态来预测行为。这样做可能会在文件系统竞态条件下导致奇怪的行为。”,但我还是想理解这里的问题所在。如果我关闭应用程序并重新启动,则上述代码中第一次检查fileExistsAtPath仍然返回NO,即使目录在先前执行代码期间已成功创建,并且我可以在组织器中看到该目录,还可以成功从目录内容中读取等等。此外,附言:没有fileExistsAtURL方法吗?

打印出你正在使用的路径,并确保它是你想要的路径。 - Hot Licks
1
无法在这台机器上进行测试,但是应该使用[newDirectoryPath path]而不是[newDirectoryPath absoluteString],对吗? - Joachim Isaksson
@Joachim Isaksson - 就是这样 - 谢谢 - Gruntcakes
1个回答

20
如果你有一个 NSURL 对象,那么使用`-absoluteURL`方法得到的路径将带有 "file://" 前缀,并不适用于 NSFileManager。例如:`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");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接