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.
我知道文档说这个:
Attempting to predicate behavior based on the current state of the
file system or a particular file on the file system is not
recommended. Doing so can cause odd behavior in the case of file
system race conditions.
但我想了解这里的问题 – 如果我关闭应用程序并重新启动它,那么上面代码中对fileExistsAtPath的第一次检查仍然返回NO,即使该代码先前在代码的执行过程中已成功创建,我可以在管理器中看到该目录,我也可以成功地从目录的内容等中读取.
附:有没有fileExistsAtURL:方法?
解决方法
如果您有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"); }