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

laj*_*jos 45 cocoa objective-c

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

Mat*_*ard 72

使用NSFileManagerfileExistsAtPath:isDirectory:方法.请参阅苹果的文档在这里.


Rya*_*tta 13

Apple在NSFileManager.h中提供了一些关于检查文件系统的好建议:

"尝试操作(比如加载文件或创建目录)并优雅地处理错误要好于提前判断操作是否成功.试图根据当前的状态来预测行为.文件系统或文件系统上的特定文件在文件系统竞争条件下鼓励奇怪的行为."


laj*_*jos 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.
Run Code Online (Sandbox Code Playgroud)


rjs*_*ing 7

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!
}
Run Code Online (Sandbox Code Playgroud)