Cocoa と Objective-C にフォルダーが存在するかどうかを確認するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/99395

  •  01-07-2019
  •  | 
  •  

質問

Objective-Cを使用してCocoaにフォルダー(ディレクトリ)が存在するかどうかを確認するにはどうすればよいですか?

役に立ちましたか?

解決

使用 NSFileManagerさんの fileExistsAtPath:isDirectory: 方法。Apple のドキュメントを参照してください ここ.

他のヒント

NSFileManager.h には、ファイル システムのチェックに関する Apple からの良いアドバイスがいくつかあります。

「操作 (ファイルのロードやディレクトリの作成など) を試行してエラーを適切に処理する方が、操作が成功するかどうかを事前に判断するよりもはるかに優れています。ファイルシステムまたはファイルシステム上の特定のファイルの現在の状態に基づいて動作を予測しようとすると、ファイルシステムの競合状態に直面した場合に奇妙な動作が促進されます。」

[NSFileManager fileExistsAtPath:isDirectory:]

Returns a Boolean value that indicates whether a specified file exists.

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory

Parameters
path
The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method will return NO.

isDirectory
Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.

Return Value
YES if there is a file or directory at path, otherwise NO. If path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.

NSFileManager は、ファイル関連の API を探すのに最適な場所です。必要な特定の API は次のとおりです。 - fileExistsAtPath:isDirectory:.

例:

NSString *pathToFile = @"...";
BOOL isDir = NO;
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:pathToFile isDirectory:&isDir];

if(isFile)
{
    //it is a file, process it here how ever you like, check isDir to see if its a directory 
}
else
{
    //not a file, this is an error, handle it!
}

あなたが持っているなら NSURL オブジェクトとして path, 、パスを使用して変換することをお勧めします。 NSString.

NSFileManager*fm = [NSFileManager defaultManager];

NSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory 
                           inDomains:NSUserDomainMask] objectAtIndex:0]                           
                                 URLByAppendingPathComponent:@"photos"];

NSError *theError = nil;
if(![fm fileExistsAtPath:[path path]]){
    NSLog(@"dir doesn't exists");
}else
    NSLog(@"dir exists");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top