转自:http://www.jianshu.com/p/3355373e0b81
使用NSFileManager
- 文件系统接口
- 允许访问文件夹内容
- 创建,重命名,删除文件,修改文件和文件属性,以及Finder对所有文件系统任务执行的一般操作
- 访问
NSFileManager,使用共享的管理器对象NSFileManager *fileManager = [NSFileManager defaultManager];
-
允许对
NSFileManager设置代理- 用于当文件管理器完成如复制或移动文件操作时,接受相应的信息
-
需要创建自己的
NSFileManager实例,而不是使用共享实例NSFileManager *newFileManager = [[NSFileManager alloc] init]; newFileManager.delegate = self;
-
获取一个文件夹的内容
contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:-
简单返回文件夹内容的
NSURLNSURL *folderURL = [NSURL fileURLWithPath:@"/Applications/"]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error = nil; NSArray *folderContents = [fileManager contentsOfDirectoryAtURL:folderURL includingPropertiesForKeys:nil options:0 error:error]; -
folderContents包含指向该文件夹中每一项的NSURL
-
访问单独的
NSURL对象,获取指向的文件信息resourceValuesForKeys:error:-
返回
NSDictionary,包含每一项指向的文件的属性//新建一个数组,包含想要了解的属性 //这里包含文件大小,修改日期 NSArray *attributes = [NSArray arrayWithObjects:NSURLFileSizeKey,NSURLContentModificationDateKey,nil]; //获得返回的结果 //anURL是一个NSURL对象,想要了解的文件(夹) //这里不关心出错信息 NSDictionary *attributesDictionary = [anURL resourceValuesForKeys:attributes error:nil]; //获取文件大小 NSNumber *fileSizeInBytes = [attributesDictionary objectForKey:NSURLFileSizeKey]; //获取最近修改日期 NSDate *lastModifiedDate = [attributesDictionary objectForKey:NSURLContentModificationDateKey];
-
在
NSFileManager列出文件夹内容时,预抓取属性-
节省时间
NSArray *attributes = [NSArray arrayWithObjects:NSURLFileSizeKey,NSURLContentModificationDateKey,nil]; NSArray *folderContents = [fileManager contentsOfDirectoryAtURL:folderURL includingPropertiesForKeys:attributes //就是这里 options:0 error:error];
-
- 创建目录
[fileManager createDirectoryAtURL:anURL withIntermediatetDirectories:YES attributes:nil error:nil];withIntermediatetDirectories:YES创建额外需要的文件夹,创建父目录不存在的子目录,自动将父目录创建
- 创建文件
[fileManager createFileAtPath:aPath contents:someData attributes:nil];
- 删除文件
[fileManager removeItemAtURL:anURL error:nil];- 这样删除不会移至垃圾箱
- 移动文件
[file moveAtURL:sourceURL toURL:destinationURL error:nil];-> BOOL
- 复制文件
[file copyItemAtURL:sourceURL toURL:destinationURL error:nil];-> BOOL
文/扬扬扬(简书作者)
原文链接:http://www.jianshu.com/p/3355373e0b81
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文链接:http://www.jianshu.com/p/3355373e0b81
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

本文介绍如何使用NSFileManager进行文件系统操作,包括创建、删除、移动、复制文件及获取文件夹内容等基本功能。
2113

被折叠的 条评论
为什么被折叠?



