如何检查 Cocoa 和 Objective-C 中是否存在文件夹?
-
01-07-2019 - |
题
如何使用 Objective-C 检查 Cocoa 中是否存在文件夹(目录)?
解决方案
使用 NSFileManager
的 fileExistsAtPath:isDirectory:
方法。请参阅苹果的文档 这里.
其他提示
Apple 在 NSFileManager.h 中提供了一些关于检查文件系统的好建议:
“尝试一个操作(例如加载文件或创建目录)并优雅地处理错误比尝试提前确定操作是否会成功要好得多。尝试根据文件系统的当前状态或文件系统上的特定文件来预测行为会在面对文件系统竞争条件时鼓励奇怪的行为。”
[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");
不隶属于 StackOverflow