Objective-Cを使用してCocoaにフォルダ(ディレクトリ)が存在するかどうかを確認するにはどうすればよいですか?
42895 次
5 に答える
73
NSFileManager
のfileExistsAtPath:isDirectory:
メソッドを使用します。こちらの Apple のドキュメントを参照してください。
于 2008-09-19T03:52:50.310 に答える
13
ファイルシステムのチェックに関するNSFileManager.hのAppleからのいくつかの良いアドバイス:
「操作(ファイルのロードやディレクトリの作成など)を試行し、操作が成功するかどうかを事前に把握しようとするよりも、エラーを適切に処理する方がはるかに優れています。ファイルシステムまたはファイルシステム上の特定のファイルは、ファイルシステムの競合状態に直面して奇妙な動作を助長しています。」
于 2010-09-23T08:58:39.170 に答える
10
[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.
于 2008-09-19T03:56:23.483 に答える
8
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!
}
于 2012-04-21T12:10:21.783 に答える
2
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");
于 2013-04-11T19:09:01.833 に答える