浅谈iOS的文件操作

2016-03-04 0 923

一、沙盒路径

沙盒主路径:是程序运行期间系统会生成一个专属的沙盒路径,应用程序在使用期间非代码的文件都存储在当前的文件夹路径里面
我们通过以下代码可以打印出沙盒主路径

NSString *homePath =NSHomeDirectory(); NSLog(@\"%@\",homePath);

我们根据打印出的路径前往文件夹可以进入包含 Documents Library 和 tmp文件夹的文件夹 这个就是沙盒主路径

浅谈iOS的文件操作


Documents:用来存储永久性的数据的文件 程序运行时所需要的必要的文件都存储在这里(数据库)itunes会自动备份这里面的文件
Library:用于保存程序运行期间生成的文件
Caches:文件夹用于保存程序运行期间产生的缓存文件
Preferences:主要是保存一些用户偏好设置的信息,一般情况下,我们不直接打开这个文件夹 而是通过NSUserDefaults进行偏好设置的存储
tmp:临时文件夹—程序运行期间产生的临时岁骗会保存在这个文件夹中 通常文件下载完之后或者程序退出的灰自动清空此文件夹itunes不会备份这里的数据。 ~~~~tips: 由于系统会清空此文件夹所以下载或者其他临时文件若需要持久化请及时移走

//第一个参数:要查询的文件的路径 //第二个参数:要查询路径所属的用户 iOS是单用户 //第三个参数的意思 YES是绝对路径 NO是相对路径 //区别于OS-X系统 iOS应用文件夹中通常只有一个文件路径 由于OC同时支持的苹果系列产品的开发 在MacOS里面会同时存在很多软件 通常生成的路径放在一个数组里面 //iOS端一次只有一个应用 所以取数组唯一的一个元素即可 NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO); NSLog(@\"%@\",documentArray);//打印的结果是 \"~/Documents\" NSString *documentPath = [documentArray firstObject]; NSLog(@\"documentPath = %@\",documentPath);//结果是 ~/Documents 对比以上我们可以打印试着获取几个路径 NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]; NSLog(@\"libraryPath = %@\",libraryPath); NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject]; NSLog(@\"ChchesPath = %@\",cachesPath); NSString *preferencePath =[libraryPath stringByAppendingString:@\"/preferences\"]; NSLog(@\"%@\",preferencePath);

另外 在这里值得我们注意的一点是:.app的路径 iOS 8 之前bundle和tmp等文件统一放在主路径下(home)—iOS 8 之后boundle放在了container文件夹的下面

二、简单对象写入文件

1、NSString 写入文件 读取
//准备字符串 NSString *string  = @\"I love my iOS teacher\"; //2 准备路径 NSString *path =NSHomeDirectory();
    path = [path stringByAppendingString:@\"/见哥.txt\"]; //3 写入文件 //    3.1第一个参数 路径 //    3.2第二个参数 是否进行线性操作(YES保证发生意外时有中转文件来保存信息 直至写入完成 但是损耗大. NO的时候写入速度快 但是没有安全保障) //    3.3第三个参数 编码方式 //    3.4第四个参数 错误对象 [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

读取文件

NSString *contentString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSLog(@\"%@\",contentString);
2、NSArray 写入文件 读取
NSArray *array = [NSArray arrayWithObjects:@\"Lily\",@\"Yucui\",@\"Star\",@\"Ling\",@\"Wenqi\",@\"Yangyang\", nil]; NSString *docuPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    docuPath =[docuPath stringByAppendingString:@\"/Lady.txt\"]; //写入文件 [array writeToFile:docuPath atomically:YES]; NSLog(@\"docuPath = %@\",docuPath); //取出文件 NSArray *array1 = [NSArray arrayWithContentsOfFile:docuPath]; NSLog(@\"%@\",array1);
3、NSDictionary 写入文件 读取

类比于以上

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@\"SB\",@\"1\",@\"38\",@\"2\",@\"孩子\",@\"3\", nil]; NSString *prefePath =[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
    prefePath = [prefePath stringByAppendingString:@\"/preferences/SB.txt\"];
    [dict writeToFile:prefePath atomically:YES]; NSDictionary *dic =[NSDictionary dictionaryWithContentsOfFile:prefePath];
4、NSData对象写入 读取

我们搞一张图片 (波多老师哟~) 为例

UIImage *image =[UIImage imageNamed:@\"11.jpg\"]; NSString *homePath =NSHomeDirectory();
    homePath = [homePath stringByAppendingString:@\"/Sex.jpg\"]; NSData *data = UIImageJPEGRepresentation(image, 1);
    [data writeToFile:homePath atomically:YES]; //读取图片 UIImageView *aImageView  = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    aImageView.image = [UIImage imageWithContentsOfFile:homePath];
    [self.view addSubview:aImageView];

三、复杂对象写入文件

简单对象可以通过writeTofile写入对象 但是复杂对象没有writeToFile的方法写入文档,所以我们需要借助归档和反归档,将复杂对象转化成简单对象,写入文档
首先, 我们x-code新建一个类 SingleVip 继承与NSObject 遵守 NSCoding协议

.h #import <Foundation/Foundation.h> @interface SingleVip : NSObject<NSCoding> @property(nonatomic,strong)NSString *name; @property(nonatomic,strong)NSString *assets;//资产 @property(nonatomic,strong)NSString *car; @property(nonatomic,assign)int age; @end .m #import \"SingleVip.h\" //定义成宏 方便下面使用 也可以减少出错 #define kName @\"name\" #define kAssets @\"assets\" #define kCar @\"car\" #define kAge @\"age\" @implementation SingleVip #pragma mark---NSCoding必须实现的两个----- //编码 这个方法就是将对象转化成data的时候会执行的 - (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_name forKey:kName];
    [aCoder encodeObject:_assets forKey:kAssets];
    [aCoder encodeObject:_car forKey:kCar];
    [aCoder encodeInt:_age forKey:kAge];
} //反编码 - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) {
        _name = [aDecoder decodeObjectForKey:kName];
        _assets = [aDecoder decodeObjectForKey:kAssets];
        _age= [aDecoder decodeIntForKey:kAge];
        _car = [aDecoder decodeObjectForKey:kCar];
    } return self;
} @end

在以上基础上 我们创建一个SingleVip类的实例变量 进行归档和反归档的操作 直接上代码吧、、、往下看

SuperMan *man =[SuperMan new];
    man.name = @\"见哥\";
    man.age = 18;
    man.car = @\"凤凰牌大联合\";
    man.assets = @\"穷类屌蛋精光\"; //    //准备路径 NSString *homePath =NSHomeDirectory();
    homePath = [homePath stringByAppendingString:@\"/钻石王老五.txt\"]; //    //创建数据对象 用来存放vip对象 NSMutableData *data =[NSMutableData data]; //    //创建归档对象 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; //    //开始归档 [archiver encodeObject:vip forKey:@\"vip\"]; //    //完成归档 [archiver finishEncoding]; //    //写入文件 [data writeToFile:homePath atomically:YES]; //反归档 //将文件里面的data对象读取出来 NSData *_data = [NSData dataWithContentsOfFile:homePath]; //创建反归档对象 NSKeyedUnarchiver *unArchiver =[[NSKeyedUnarchiver alloc]initForReadingWithData:_data];
    SingleVip *_vip = [unArchiver decodeObjectForKey:@\"vip\"];
    [unArchiver finishDecoding];//完成反归档 NSLog(@\"%@\",_vip.name);

在这里有一点是需要我们区分的,归档并不是数据持久化的方式 而是辅助复杂对象转化成简单对象的一种方式 其实真正实现数据持久化的仍然是写入文件writeToFile

iOS常见的数据持久化的方式 主要有以下几点:
// plist (属性列表)
// NSUserDefaults 偏好设置 单例
// writeToFile 写入文件
// SQLite 数据库
// CoreData

4、文件操作

我们以一张图片为例

#define K_IMG @\"http://news.eastday.com/images/thumbnailimg/month_1511/201511170142052896.jpg\" __weak typeof(self)temp = self; NSURLSessionDownloadTask *downLoadTask = [[NSURLSession sharedSession]downloadTaskWithURL:[NSURL URLWithString:K_IMG] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { //data对象 NSData *data = [NSData dataWithContentsOfURL:location]; //创建文件管理者对象 NSFileManager *fileManeger = [NSFileManager defaultManager]; //文件夹路径操作 NSString *homePath = NSHomeDirectory();
        homePath = [homePath stringByAppendingPathComponent:@\"男神\"];
        [fileManeger createDirectoryAtPath:homePath withIntermediateDirectories:YES attributes:nil error:nil ];

        homePath = [homePath stringByAppendingString:@\"/god\"];
        [fileManeger createFileAtPath:homePath contents:data attributes:nil]; /*
        UIImage *aImage = [UIImage imageWithContentsOfFile:homePath];
        UIImageView *aImageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        aImageView.image = aImage;
        [temp.view addSubview:aImageView];
         */ //这里以删除文件为例 BOOL res=[fileManeger removeItemAtPath:homePath error:nil]; if (res) { NSLog(@\"文件删除成功\");
        }else NSLog(@\"文件删除失败\"); NSLog(@\"文件是否存在: %@\",[fileManeger isExecutableFileAtPath:homePath]?@\"YES\":@\"NO\");
    }];
    [downLoadTask resume];

文/刘高见(简书作者) 原文链接:http://www.jianshu.com/p/e41e73f4edec 

遇见资源网 IOS 浅谈iOS的文件操作 http://www.ox520.com/23028.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务