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 に答える
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
}

次に、メソッドを呼び出してdefaultManager()、ファイルが存在するかどうかを確認します。

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