iOS开发-数据持久化 :沙盒,归档反归档,NSFileManager文件管理器(单例)

来源:互联网 发布:多通道数据采集系统 编辑:程序博客网 时间:2024/05/20 17:08
1. 沙盒
        每一个应用都有一个沙盒机制,主要缓存用户信息,比如密码,音频视频,图片,登陆文件,安全性非常高,不以盗取。
能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此。

   documents文件夹,主要用来存放客户端缓存数据,比如文字,图片,音频,视频,等数据
   library文件夹,主要用于存放系统缓存数据
  (library) preferences文件夹,主要存放系统配置文件
   注意:以上文件夹存放位置的数据不会因为应用重启而被清空,除非是应用删除
  tmp文件夹,临时缓存文件夹数据,缓存系统的临时文件,当应用重启后,该文件夹的数据会被清空

NSArray*array =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
   
// 获取documentPath 路径
   NSString*documentPath = [arraylastObject];

 // 1 将字符串写入文件
   
NSString *name =@"大水杯";
   
   
// 拼接一个txt文件路径
   
NSString *txtFilePath = [documentPathstringByAppendingPathComponent:@"yuPeng"];
   
   
/**
     *
     * 
参数1写入路径
     * 
参数2是否写保护
     * 
参数3编码格式
     *
     */

   
BOOL result = [namewriteToFile:txtFilePathatomically:YESencoding:NSUTF8StringEncodingerror:nil];
   
if (result) {
       
NSLog(@"写入成功");
    }
else{
       
NSLog(@"写入失败");

    }
   
   
// 2  将数组写入文件
   
// @()  转换类型
   
// @{}  - > 字典
   
// @[]  - > 数组
   
// @()  - > 对象类型,NSNumber
   
NSArray *array1 =@[@"猫猫",@"狗狗",@"等三包",@(12)];
   
NSString *arrayFilePath = [documentPathstringByAppendingPathComponent:@"yuPeng.xml"];
   
// 写入
   
BOOL result1 = [array1writeToFile:arrayFilePathatomically:YES];
   
if (!result1) {
       
NSLog(@"数组写入失败");
    }
 
// 3 将字典写入文件
   
NSDictionary *dic =@{@"name":@"猫猫",@"sex":@"不详"};
   
   
NSString *dicPath = [documentPathstringByAppendingPathComponent:@"yuPeng.plist"];
    [dic writeToFile:dicPath atomically:YES];

2. 归档反归档
其实就是对模型的处理{ 归档:就是对复杂数据的存储
                   反归档:就是将归档的数据取出来}

在sutdent.h 文件里

在sutdent.m 文件里

 
NSArray*array =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
   
// 获取documentPath 路径
   NSString*documentPath = [arraylastObject];



3.NSFileManager文件管理器(单例)
{ 获取docunment 路径
   在docunment 路径下拼接一个文件夹
   创建文件夹[manger create]
   在该文件夹下拼接一个文件路径
   将内容写入文件下
 }
注意:拼接文件不代表本地就有该文件或者文件夹路径其实就是一个字符串


0 0