52

对不起,今天的愚蠢问题 2。是否可以确定文件是否包含在 App Bundle 中?我可以访问文件没问题,即

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];

但无法弄清楚如何首先检查文件是否存在。

问候

戴夫

4

5 回答 5

71
[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];
于 2010-01-07T23:04:58.810 回答
16

这段代码对我有用......

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName])
{
    NSLog(@"File exists in BUNDLE");
}
else
{
    NSLog(@"File not found");
}

希望它会帮助某人...

于 2013-12-15T06:54:25.113 回答
9

如果资源不存在,pathForResource 将返回 nil。用 NSFileManager 再次检查是多余的。

对象-C:

 if (![[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"plist"]) {                                              
      NSLog(@"The path could not be created.");
      return;
 }

斯威夫特 5:

 guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else {
      print("The path could not be created.")
      return
 }
于 2016-02-24T18:46:34.063 回答
4
NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"];
    if(![fileManager fileExistsAtPath:path])
    {
        // do something
    }
于 2010-03-19T15:57:54.367 回答
1

与@Arkady 相同,但使用 Swift 2.0:

首先,调用一个方法mainBundle()来帮助创建资源的路径:

guard let path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "txt") else {
    NSLog("The path could not be created.")
    return
}

然后,调用 on 方法defaultManager()检查文件是否存在:

if NSFileManager.defaultManager().fileExistsAtPath(path) {
    NSLog("The file exists!")
} else {
    NSLog("Better luck next time...")
}
于 2015-07-25T10:52:10.353 回答