UI基础:DataPersistent.沙盒

沙盒是系统为每一个应用程序生成的一个特定文件夹,文件夹的名字由一个十六进制数据组成,每一个应用程序的沙盒文件名都是不一样的,是由系统随机生成的.

沙盒主目录:

    NSString *homePath = NSHomeDirectory();

沙盒内放有三个主要目录文件夹:1.Documents 2.Library 3tmp

1.Documents 存放是一些比较重要的文件,但是放入Documents中的文件不能过大.

2.Library 是一个资源库,存储一些不太重要的数据,相对比较大一些,里面有两个子文件夹:Caches文件夹,用于缓存文件,图片缓存,视频缓存,网页缓存,应用程序缓存就是清除这个文件夹,Preferences文件夹,系统偏好设置,用户对应用程序的设置,比如:用户名和密码.perferences路径无法找到,通过NSUserDefaults

3.tmp 存放一些临时文件,比如下载的压缩包Zip,解压后立即把压缩包删除.

 

NSSearchPathDirectory这个类使用来查找文件目录.

如:NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

//第一个参数:问价名称    

//第二个参数:确定搜索域

//第三个参数:确定是相对路径还是绝对路径,YES 绝对  NO 相对

 

NSBundle   包文件   //相当于右键显示包内容

ios8之前包和沙盒在同一个目录下,iOS8之后,app单独储存到一个独立的文件目录下.

.app文件只能读不能写(readOnly),从AppStore下载下来的是这个包,程序上传的时候也是这个包.

 

//NSFileManager 文件管理工具,主要用于添加.删除.移动.拷贝等,继承自NSObject.

下面的代码示例:

一.在Caches文件夹下创建一个Image文件

1.获取Caches文件路径

    NSString *cachesPath =   [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];//先获取Caches路径

2.拼接Image文件夹路径

   NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"imagessss"]

    //stringByAppendingFormat 拼接上什么就是什么;

    //stringByAppendingPathExtension 会在拼接内容前加一个 .

    //stringByAppendingString 拼接上什么就是什么

3.创建文件管理者

NSFileManager是一个单例

NSFileManager *manager = [NSFileManager defaultManager];

4.先判断这个文件夹是否存在

BOOL isExist = [manager fileExistsAtPath:imagePath];

 

    if (!isExist) {

 

        //不存在

 

       BOOL isSucess = [manager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];

 

        NSLog(@"%@",isSucess ? @"创建成功" : @"创建失败");

 

    }

    //删除文件

    if ([manager fileExistsAtPath:imagePath]) {        

      BOOL isSucess = [manager removeItemAtPath:imagePath error:nil];

      NSLog(@"%@",isSucess ? @"删除成功" : @"删除失败");        

    }

 

二.拷贝文件,把包中的plist文件,拷贝到Image文件夹下

1.先获取plist文件的路径,该文件必须事先就存在

    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"NB" ofType:@"plist"];

2.获取目的地路径,就是Image在沙盒中的路径

    NSString * nBPath =  [imagePath stringByAppendingPathComponent:@"NB.plist"];

3.开始拷贝   

    if (![manager fileExistsAtPath:nBPath]) {

        //不存在文件路径的时候拷贝

      BOOL isSuccess =   [manager copyItemAtPath:bundlePath toPath:nBPath error:nil];

        NSLog(@"%@",isSuccess ? @"拷贝成功" : @"拷贝失败");

    }

三.移动文件,把把nBPath下的NB.plist文件移动到Document下

1.移动之前的路径 nBPath

2.获取Documents路径,然后拼接@"NB.plist" 

  NSString *toPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"NB.plist"];

3.移动

   BOOL isSuccess =  [manager moveItemAtPath:nBPath toPath:toPath error:nil];

    NSLog(@"%@",isSuccess ? @"移动成功" : @"移动失败");

 

//NSUserDefaults的数据持久化

 NSUserDefaults继承自NSObject,也是一个单例,通过KVC模式去赋值,存取数据时所操作的内容,都存放在perference

创建用户索引对象

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setInteger:100 forKey:@"money"];

 [defaults synchronize]; //立即同步操作,只要修改了perferences文件中plist文件,就要立即同步.

 

  //NSUserDefault还能操作其他数据类型:NSDictionary ,NSArray,NSString,NSData,NSNumber,BOOL,NSInteger

 //NSUserDefaults 一般存储一些比较小的数据,大部分都用来存数值

模仿首次登录:

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

    BOOL isFirst = [userDefault boolForKey:@"isFirst"];

       if (isFirst == NO ) {

        NSLog(@"第一次登录");

        [userDefault setBool:YES forKey:@"isFirst"];

        [userDefault synchronize];

    }else{

        NSLog(@"不是第一次登录");

    }

------------------------------------------数据写入文件-----------------------------------------

一.字符串写入文件,将字符串写入Documents文件夹下

1.获取Document文件路径

    NSString *docmentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

2.string.txt就是字符串要写入的文件,拼接.

    NSString *stringPath = [docmentsPath stringByAppendingPathComponent:@"string.txt"];

3.准备要写入的字符串

   NSString *string = @"马震和优衣库你选哪一个?";

4.写入

    NSError *error = nil;

    BOOL isSuccess = [string writeToFile:stringPath atomically:YES encoding:NSUTF8StringEncoding error:&error];

    NSLog(@"%@",isSuccess ? @"字符串写入成功" : @"字符串写入失败");

第一个参数:要写入的文件路径,如果如果此文件路径下没有此文件,系统会自动创建一个文件

第二个参数:判断是否需要生成辅助文件,为了保护在多线程下的安全.

第三个参数:编码格式.

第四个参数:错误

     //字符串取值操作

  NSString *getString = [[NSString alloc]initWithContentsOfFile:stringPath encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",getString);

二.数组的写入,写入到library路径下的array.txtzhong

1.获取library路径

  NSString *librarayPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];

2.将array.txt拼接到libraryPathhou

    NSString *arrayPath = [librarayPath stringByAppendingPathComponent:@"array.txt"];

 3.准备写入文件的数组

    NSArray *array = @[@"狗狗",@"小鱼",@"咪咪",@"山炮"];

 4.写入    

    BOOL isSuccess = [array writeToFile:arrayPath atomically:YES];

    NSLog(@"%@",isSuccess ? @"数组写入成功" : @"数组写入失败");

//数组读取 

     NSArray *getArray = [NSArray arrayWithContentsOfFile:arrayPath];

     NSLog(@"%@",getArray);

 三.字典写入文件,写入到caches下的dictionary.txt中.

1.现获取caches的路径

    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];

2.拼接

    NSString * dictionaryPath = [cachesPath stringByAppendingPathComponent:@"dictionary.txt"];

3.准备写入的字典

   NSDictionary *dictionary = @{@"a":@"123",@"b":@"456",@"c":@"789"};

4.写入

    BOOL isSuccess =  [dictionary writeToFile:dictionaryPath atomically:YES];

    NSLog(@"%@",isSuccess ? @"字典写入成功" : @"字典写入失败");

//读取

    NSDictionary *getDictionary = [NSDictionary dictionaryWithContentsOfFile:dictionaryPath];

    NSLog(@"%@",getDictionary);

-----------------------------------------------NSData(二进制流)文件写入------------------------------

写入tem下的data.txt

1.获取tem的路劲

 NSString *tmpPath = NSTemporaryDirectory();

2.data.txt拼接到tmpPath后

 NSString *dataPath = [tmpPath stringByAppendingPathComponent:@"data.txt"];

 3.准备写入的NSData对象

  NSString *string = @"叔叔,咱们约吧!";

  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];//字符串转为NSData

4.写入

    BOOL isSuccess = [data writeToFile:dataPath atomically:YES];

    NSLog(@"%@",isSuccess ? @"Data写入成功" : @"Data写入失败");

  //data从文件中取值

    NSData *getData = [NSData dataWithContentsOfFile:dataPath];

    NSLog(@"%@",getData);

    NSString *getString = [[NSString alloc]initWithData:getData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",getString);

----------------------------------------------复杂对象的归档和反归档-----------------------------------

复杂对象是无法写入文件的,要想把复杂对象写入文件,必须要把它转换为data(二进制流)才能写入.

归档:归档的实质就是把其他类型数据先转换为NSData,再写入文件.这里以person作为复杂对象举例.

能够进行归档和反归档的复杂对象必须遵守NSCoding协议.

一.归档

1.创建复杂对象Person

    Person *person = [[Person alloc]initWithName:@"rose" gender:@"girl" age:18];

 2.创建可变data存储压缩后的数据

//   NSKeyedArchiver 压缩工具,继承自NSCoder,主要用于编码

    NSMutableData *data= [NSMutableData data];

    NSKeyedArchiver *archiver =[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

3.使用压缩工具将person对象压缩到data

    [archiver encodeObject:person forKey:@"person"];

4.完成压缩,需停止压缩工具

    [archiver finishEncoding];

 5.将压缩后的文件写入person.txt文件中

    NSString *homePath = NSHomeDirectory();

    NSString *personPath = [homePath stringByAppendingPathComponent:@"perosn.txt"];

    BOOL isSuccess = [data writeToFile:personPath atomically:YES];

    NSLog(@"%@",isSuccess ? @"person 写入成功" : @"person 写入失败");

 二.反归档

 复杂对象的读取叫做反归档

 NSKeyedUnarchiver 反归档工具

1.获取文件中的数据,a.文件路径b.找一data对象接收读取结果

    NSData *unData = [NSData dataWithContentsOfFile:personPath];

 2.创建反归档工具

    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unData];

 3.解压

     Person *unPerson = [unArchiver decodeObjectForKey:@"person"];

 4.停止解压

     [unArchiver finishDecoding];

     NSLog(@"%@",unPerson);

~~~~~~数组的归档和反归档~~~~~~~~ 

集合如果想进行反归档和归档,那么它里面的元素也必须遵循NSCoding协议.

    Person *person1 = [[Person alloc]initWithName:@"范冰冰" gender:@"男" age:30];

    Person *person2 = [[Person alloc]initWithName:@"大黑牛" gender:@"女" age:28];

    NSArray *array = @[person1,person2];

//创建压缩数据

    NSMutableData *data = [NSMutableData data];

 //归档工具的创建

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

 //压缩归档的对象

    [archiver encodeObject:array forKey:@"array"];

 //压缩结束

     [archiver finishEncoding];

    //将文件存放到tmp目录下,array.txt

    NSString *tmpPath = NSTemporaryDirectory();

    NSString *arrayPath = [tmpPath stringByAppendingPathComponent:@"array.txt"];

    BOOL isSuccess = [data writeToFile:arrayPath atomically:YES];

    NSLog(@"%@",isSuccess ? @"数组写入成功" : @"数组写入失败");

    //通过文件路径初始化unData

    NSData *unData = [NSData dataWithContentsOfFile:arrayPath];

    //创建反归档对象

    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unData];

    //解压数据

    NSArray *unArray = [unArchiver decodeObjectForKey:@"array"];

    //停止反归档工具

    [unArchiver finishDecoding];

    NSLog(@"%@ %@",unArray[0],unArray[1]);

原文地址:https://www.cnblogs.com/shaoting/p/4758921.html