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

时间:2020-03-06 14:24:35  来源:igfitidea点击:

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

解决方案

使用NSFileManager的fileExistsAtPath:isDirectory:方法。请在此处查看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.h中提供了一些有关检查文件系统的好的建议:

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