如何确定应用程序包中是否存在文件?

Mag*_*ave 49 iphone nsbundle

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

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
Run Code Online (Sandbox Code Playgroud)

但无法弄清楚如何检查文件是否存在于那里.

问候

戴夫

Rob*_*ier 68

[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];
Run Code Online (Sandbox Code Playgroud)

  • 然而,根据[这个答案](http://stackoverflow.com/a/7487235/1226722),即使Apple建议实际__"尝试操作(例如加载文件或创建目录),检查错误,优先处理任何错误,而不是试图提前判断操作是否成功"__. (5认同)

Ark*_*ady 15

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

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

希望它会帮助某人......


cro*_*row 6

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

对象C:

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

斯威夫特4:

 guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else {
      print("The path could not be created.")
      return
 }
Run Code Online (Sandbox Code Playgroud)