xcode 当没有这样的文件时,为什么 NSFileManager 在 fileExistsAtPath 上返回 TRUE?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2455735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:11:52  来源:igfitidea点击:

Why does NSFileManager return TRUE on fileExistsAtPath when there is no such file?

iphoneobjective-cxcodensfilemanager

提问by RexOnRoids

NSFilemanager is returning true for the following, when there should not be any such file there yet. What is happening?

NSFilemanager 在以下情况下返回 true,此时不应该有任何此类文件。怎么了?

    if([myManager fileExistsAtPath:[[self documentsDirectory] stringByAppendingPathComponent:@"Music/songlist.txt"]]){

NSLog(@"file is there");

}

回答by dreamlax

The documentation for NSFileManagerseems to recommend notchecking to see if files exist, and instead just trying to read the file and handle any errors gracefully (e.g. file not founderror). What you are describing doesn't sound like a race condition—which is what the documentation's recommendation is trying to circumvent—but what happens if you just try to load the file rather than checking to see if it exists? You could, for example, try the following:

对于文件NSFileManager似乎建议检查,看是否存在的文件,而是只是试图读取该文件,并适当地处理任何错误(例如,未找到文件错误)。您所描述的听起来不像是竞争条件——这是文档的建议试图规避的——但是如果您只是尝试加载文件而不是检查它是否存在,会发生什么?例如,您可以尝试以下操作:

NSError *error;
NSStringEncoding encoding;
NSString *fileContents = [NSString stringWithContentsOfFile:fileName
                                               usedEncoding:&encoding
                                                      error:&error];

if (fileContents == nil)
{
    NSLog (@"%@", error);
}
else
{
    NSLog (@"%@", fileContents);
}

If you get a string with all of the file's contents, then the file is obviously there. If you get an error then something is up with myManager.

如果你得到一个包含所有文件内容的字符串,那么文件显然就在那里。如果出现错误,则说明myManager.

回答by markhunte

This works as expected for me.

这对我来说按预期工作。

 NSFileManager *myManager = [NSFileManager defaultManager];
NSString *documentsDirectory = NSHomeDirectory();

if([myManager fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:@"Music/songlist.txt"]]){

    NSLog(@"file is there");

}

回答by Jordan

Print this out and see if it is what you expect.

打印出来看看它是否是你所期望的。

NSLog(@"Directory: %@", [[self documentsDirectory] stringByAppendingPathComponent:@"Music/songlist.txt"]];

Also, check that you are defining myManager correctly.

另外,请检查您是否正确定义了 myManager。