IOS为每个APP都分配了个本地文件夹。在Documents目录下存放比较大的用户数据。Library是开发者最频繁使用的文件夹,下面可以新建子文件夹。tmp是临时文件夹,每次启动时会自动清空,或者系统收到存储警告时也会清空。
- NSSearchPathForDirectoriesInDomains
- NSFileManager
- NSFileHandle
NSSearchPathForDirectoriesInDomains
用NSSearchPathForDirectoriesInDomains就能访问APP的本地文件夹,可以用预设的宏快速定位到常用文件夹,例如NSDocumentDirectory就定位到Documents文件夹,看名字也能猜到。
NSArray *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
可以通过UIView/UILabel/UIButton封装任意组件,组内内封装基板逻辑,开发者提供数据,将基本逻辑中可定制的业务封装成delegate
NSFileManager
NSFileManager提供文件和文件夹的管理功能,能创建,更新,删除文件和文件夹,还能读取文件属性和内容。参数是NSURL或NSString作为path。常用方法:
createDirectoryAtPath:创建文件夹
createFileAtPath:创建文件
fileExistsAtPath:路径下是否存在该文件
contentsOfDirectoryAtPath:读取文件夹内容
contentsAtPath:读取文件内容
attributesOfItemAtPath:读取文件属性
removeItemAtPath:删除文件
将获取到的数据保存到本地cache文件夹中:
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachePath = [pathArray firstObject]; NSFileManager *fileManager = [NSFileManager defaultManager]; // 创建文件夹 NSString *dataPath = [cachePath stringByAppendingString:@"SampleData"]; NSError *creatError; [fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&creatError]; // 创建文件 NSString *listDataPath = [dataPath stringByAppendingPathComponent:@"list"]; NSData *listData = [@"abc" dataUsingEncoding:NSUTF8StringEncoding]; // 将字符串通过 UTF8 编码方式变成二进制流 [fileManager createFileAtPath:listDataPath contents:listData attributes:nil]; // 查询 & 删除文件 BOOL fileExist = [fileManager fileExistsAtPath:listDataPath]; if (fileExist) { // 如果文件存在就先删除 [fileManager removeItemAtPath:listDataPath error:nil]; }
NSFileHandle
NSFileHandle可以读写文件,常用方法:
fileHandleForReadingAtPath:读文件
fileHandleForWritingAtPath:写文件
fileHandleForUpdatingAtPath:更新文件
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:listDataPath]; [fileHandler seekToEndOfFile]; // 调整到末尾,在末尾追加 [fileHandler writeData:[@"def" dataUsingEncoding:NSUTF8StringEncoding]]; [fileHandler synchronizeFile]; [fileHandler closeFile];