如何检查Cocoa和Objective-C中是否存在文件夹?

如何检查Cocoa和Objective-C中是否存在文件夹?

How to check if a folder exists in Cocoa & Objective-C?

如何使用Objective-C检查Cocoa中是否存在文件夹(目录)?


使用NSFileManagerfileExistsAtPath:isDirectory:方法。 请在此处查看Apple的文档。


苹果公司在NSFileManager.h中提供了一些有关检查文件系统的好的建议:

"尝试操作(例如加载文件或创建目录)并优雅地处理错误要比试图提前确定操作是否成功要好得多。尝试根据操作的当前状态预测行为 文件系统或文件系统上的特定文件在面对文件系统争用情况时令人鼓舞。


[NSFileManager fileExistsAtPath:isDirectory:]

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

例:

1
2
3
4
5
6
7
8
9
10
11
12
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,最好使用path将其转换为NSString

1
2
3
4
5
6
7
8
9
10
11
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");


推荐阅读