ios - 如果目录不存在,使用 NSFileManager 返回

标签 ios nsfilemanager

<分区>

我有以下代码返回给定目录中文件名的 NSArray。当目录存在时这很好用,但我想知道如何首先检查 directoryPath 中的目录是否实际存在。

NSString *directoryPath = [documentsDirectory stringByAppendingPathComponent:folderName];
NSArray *directoryContents = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:directoryPath error:nil];

最佳答案

NSFileManager 类有一个内置方法,用于检查路径中是否存在文件。

函数是这样的:

[fileManagerObject fileExistsAtPath : @"PUT_YOUR_FILE_PATH_HERE" isDirectory : YES]; //If its a file that you're looking to check then put isDirectory as NO, but if its a folder then enter YES as the parameter

这是您通常在代码中使用它的方式:

NSFileManager *fileManager = [[NSFileManager alloc] init];
if([fileManager fileExistsAtPath:@"FILE_PATH_HERE" isDirectory:NO] == YES)
{
   //Yes. The file exists, continue with your operation.
}
else
{
   //No. The file doesn't exist.
}

关于ios - 如果目录不存在,使用 NSFileManager 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089002/

上一篇:ios - MKMapview 在模拟器的 iOS-7.0 中不显示 map

下一篇:ios - 总是从 iOS 中的函数中得到 nil 值

相关文章:

ios - 如何在 Swift 3 中显示文件共享中的文件

ios - 根据 subview 大小调整 XIB 中 UIView 的大小

iOS 7 自定义 TableView 在 TabBar 下

ios - NSFileManager removeItemAtPath 多次调用时会删除整个文件夹

ios - Swift - 无法打开文件,因为您没有查看它的权限

iphone - 在模拟器上存储文件与实际 iOS 设备

iphone - 启动网站并登录 iOS

ios - 如何在 iOS 的文档目录中保存带有唯一标签的文件?

iOS根据相机看到的内容以编程方式用相机拍照

objective-c - 如何在cocoa中复制网络上的文件