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

时间:2010-03-16 15:36:13

标签: iphone objective-c xcode nsfilemanager

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

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

NSLog(@"file is there");

}

3 个答案:

答案 0 :(得分:7)

NSFileManager的文档似乎建议检查文件是否存在,而只是尝试读取文件并正常处理任何错误(例如 file not found 错误)。您所描述的内容听起来并不像竞争条件 - 这是文档建议试图规避的内容 - 但是如果您只是尝试加载文件而不是检查文件是否存在会发生什么?例如,您可以尝试以下方法:

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

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

如果你得到一个包含所有文件内容的字符串,那么文件显然就在那里。如果您收到错误,那么myManager就会出现问题。

答案 1 :(得分:0)

打印出来,看看它是否符合您的期望。

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

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

答案 2 :(得分:0)

这对我有用。

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

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

    NSLog(@"file is there");

}