iOS 初级数据持久化-沙盒机制

什么是数据持久化?数据的永久存储

为什么要坐数据持久化:存储在内存中的数据,程序关闭,内存释放,数据丢失,这种数据是临时的

数据初九化的本质:数据保存成文件,存储到程序的沙河中

1.沙盒机制

每个应用程序位于文件系统的严格限制部分

每个应用程序只能在为该程序创建的文件系统中读取文件

每个应用程序在IOS系统内都放在了统一的文件夹目录下

沙盒的本质就是一个文件夹,名字是随机分配的.

2.沙盒路径的位置

1.通过Finder查找程序沙盒相对的路径

通过代码查找程序沙盒相对路径

NSString *DocumentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"%@",DocumentPath);

2.沙盒构成

Document                   存储用户数据,需要备份的信息

Library/Caches          存储缓存文件,程序专用的支持文件

Library/Preferences          存储应用程序的偏好设置文件

.app                           程序包(IOS8时,app不存储在沙盒中,有单独的文件夹存储所有程序的app包)

tmp                             存储临时文件,比如:下载的zip包,解压后的再删除

3.获取沙盒目录路径的方法

NSHomeDirectory-------------------->沙盒主路径

NSDocumentDirectory--------------->Document文件夹

NSLibraryDirectory------------------->Library文件夹

NSCachesDirectory------------------>Caches文件夹

NSTemporaryDirectory--------------->tem文件夹

代码

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;">//1.home主目录里面有:Documents,Library,tmp和一个应用程序  
  2.     NSLog(@"Home:%@",NSHomeDirectory());  
  3.     //2.DocumentsPath路径  
  4.     NSString *DocumentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];  
  5.     NSLog(@"DocumentsPath:%@",DocumentsPath);  
  6.     //3.Libray  
  7.     NSString *librayPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];  
  8.     NSLog(@"%@",librayPath);  
  9.     //4.temp  
  10.     NSLog(@"temp:%@",NSTemporaryDirectory());  
  11.     //5.cachesPath  
  12.     NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];  
  13.     NSLog(@"cachesPath:%@",cachesPath);  
  14.     //6.user  
  15.     NSString *user = NSUserName();  
  16.     NSLog(@"user:%@",user);</span>  

------------------------------------------------>>>>简单文件写入

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;">//nsstring写入  
  2.       
  3.     //1.写入的路径  
  4.     NSString *DocumentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];  
  5.     NSLog(@"%@",DocumentPath);  
  6.     //2.拼接文件路径  
  7.     NSString *filePath = [DocumentPath stringByAppendingString:@"/myText.txt"];  
  8.     //3.准备写入的内容  
  9.     NSString *content = @"Hello World";  
  10.     [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];  
  11.     //4.读取  
  12.     NSString *readString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];  
  13.     NSLog(@"redstring : %@",readString);  
  14.       
  15.       
  16.       
  17.     //NSArray  
  18.     //1.获取documents路径  
  19.     //2.拼接文件路径  
  20.     NSString *arrayFile = [DocumentPath stringByAppendingString:@"/array.plist"];  
  21.     NSLog(@"arrayPath = %@",arrayFile);  
  22.     //3.准备内容  
  23.     NSArray * contentArray = @[@"1",@"2",@"3",@"4",@"5",];  
  24.     //4.写入  
  25.     [contentArray writeToFile:arrayFile atomically:YES];  
  26.     //5.读取  
  27.     NSArray *readArray = [NSArray arrayWithContentsOfFile:arrayFile];  
  28.     NSLog(@"readArray : %@",readArray);  
  29.       
  30.     //dictinary  
  31.     //1.拼接  
  32.     NSString *dictFile = [DocumentPath stringByAppendingString:@"/dict.plist"];  
  33.     //2.准备内容  
  34.     NSDictionary *dictcontent = @{@"1":@"a",@"2":@"b",@"3":@"c"};  
  35.     NSLog(@"%@",dictFile);  
  36.     //3.写入  
  37.     [dictcontent writeToFile:dictFile atomically:YES];  
  38.     //4.读取字典  
  39.     NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:dictFile];  
  40.     NSLog(@"dict : %@",readDict);</span>  
-------------------------------->>>NSFileManager


NSFileManager,文件管理,使用detaultManager,创建单利对象

可以创建文件夹

可以创建,移动,复制,删除文件,

可以判断文件是否存在

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;"//NSFileManager  
  2.     //创建文件夹  
  3.     //在Documents中创建一个文件夹  
  4.     NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];  
  5.     //在Documents中创建一个文件夹命名为"个人收藏"  
  6.     NSString *path = [documentsPath stringByAppendingString:@"/个人收藏"];  
  7.     //创建文件管理(单利),并创建文件夹  
  8.     [[NSFileManager defaultManager]createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];  
  9.     NSLog(@"DocumentsPath%@",documentsPath);  
  10.     //修改文件夹  
  11.     NSString *newPath = [documentsPath stringByAppendingString:@"/岛国文化"];  
  12.     [[NSFileManager defaultManager]moveItemAtPath:path toPath:newPath error:nil];  
  13.     //删除  
  14.     [[NSFileManager defaultManager]removeItemAtPath:documentsPath error:nil];  
  15.     //判断某个文件是否存在  
  16.     //返回值是BOOL,YES存在,NO不存在  
  17.     [[NSFileManager defaultManager]fileExistsAtPath:newPath];</span>  

--------------------------------------------------->>>>复杂对象写入文件(归档/反归档)

1.什么是复杂对象

1.在foundation框架内不存在的数据类

2.无法在程序内通过writeToFile类型的方法写入到文件内

3.复杂对象至少包含一个实例对象


复杂对象无法通过writeToFile:方法进行数据持久化,只能通过将复杂对象转换为NSData,通过writeToFile进行数据持久化

将复杂的对象转化为NSData,通过归档;将NSData转换为复杂对象,通过反归档

复杂对象写入文件要遵循NSCoding协议

有两个方法,代码如下:

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;">//进行归档时调用(系统调用)  
  2. -(void)encodeWithCoder:(NSCoder *)aCoder  
  3. {  
  4.     //对属性进行编码  
  5.     [aCoder encodeObject:self.name forKey:kName];  
  6.     [aCoder encodeObject:self.age forKey:kAge];  
  7. }  
  8. //进行反归档编码时  
  9. -(id)initWithCoder:(NSCoder *)aDecoder  
  10. {  
  11.   
  12.     self = [super init];  
  13.     //反编码  
  14.     if (self)  
  15.     {  
  16.         self.name = [aDecoder decodeObjectForKey:kName];  
  17.     }  
  18.     return self;  
  19. }</span>  
创建一个Person类

归档/反归档代码如下:

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;">//归档 反归档  
  2.     //创建 Person类实例对象  
  3.     Person *person1 = [[Person alloc] init];  
  4.     person1.name = @"刘杰";  
  5.     person1.age = @"39";  
  6.       
  7.     Person *person2 = [[Person alloc] init];  
  8.     person2.name = @"李士杰";  
  9.     person2.age = @"18";  
  10.     //归档使用的NSData  
  11.     NSMutableData *Person1Data = [NSMutableData data];  
  12.     //创建归档工具  
  13.     NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:Person1Data];  
  14.     //进行归档  
  15.     [archiver encodeObject:person1 forKey:kPerson1];  
  16.     [archiver encodeObject:person2 forKey:kPerson2];  
  17.   
  18.     //完成转换  
  19.     [archiver finishEncoding];  
  20.     //找到路径  
  21.     NSString *docunment = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];  
  22.     //拼接文件路径  
  23.     NSString *personPath = [docunment stringByAppendingString:@"/刘杰.xxoo"];  
  24.     //写入文档  
  25.       
  26.     [Person1Data writeToFile:personPath atomically:YES];  
  27.     NSLog(@"%@",docunment);  
  28.       
  29.     //反归档  
  30.     //通过文件路径,获取data数据  
  31.     NSData * unData = [NSData dataWithContentsOfFile:personPath];  
  32.       
  33.     //反归档工具  
  34.     NSKeyedUnarchiver *unAechiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:unData];  
  35.       
  36.     //反归档  
  37.     Person *p1 = [unAechiver decodeObjectForKey:kPerson1];  
  38.     Person *p2 = [unAechiver decodeObjectForKey:kPerson2];  
  39.     //结束反归档  
  40.     [unAechiver finishDecoding];  
  41.       
  42.     NSLog(@"name:%@",p1.name);  
  43.     NSLog(@"name :%@",p2.name);  
  44. </span>  


单个归档.反归档

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;">    //获取Documents路径  
  2.     NSString *DocumentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];  
  3.     //拼接文件路径  
  4.     NSString *filePath = [DocumentsPath stringByAppendingString:@"/PersonArray.plist"];  
  5.     //实例一个对象  
  6.      
  7.      Person *p1 = [[Person alloc] init];  
  8.     p1.name = @"别闹了";  
  9.     p1.age = @"1";  
  10.     //归档  
  11.     [NSKeyedArchiver archiveRootObject:p1 toFile:filePath];  
  12.     //反归档  
  13.     Person *p2 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];  
  14.     NSLog(@"name: %@",p2.name);</span>  

多个归档/反归档

[objc]  view plain  copy
  1. <span style="font-family:SimHei;font-size:18px;"//获取Documents路径  
  2.     NSString *DocumentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];  
  3.     //拼接文件路径  
  4.     NSString *filePath = [DocumentsPath stringByAppendingString:@"/PersonArray.plist"];  
  5.     //实例一个对象  
  6.     Person *pn1 = [[Person alloc] init];  
  7.     pn1.name = @"TOM";  
  8.     pn1.age = @"12";  
  9.     Person *pn2 = [[Person alloc] init];  
  10.     pn2.name = @"KIM";  
  11.     pn2.age = @"18";  
  12.       
  13.     NSArray *array = @[pn1,pn2];  
  14.      //归档  
  15.     [NSKeyedArchiver archiveRootObject:array toFile:filePath];  
  16.     //反归档  
  17.     NSArray *a = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];  
  18.     NSLog(@"%@,%@",[a[0] name],[a[1] name]);</span>  


沙盒机制:

简单对象写入文件,只能是NSString,NSArray,NSDictionary,NSData

复杂的对象写入文件,遵守NSCoding协议,实现代理方法

猜你喜欢

转载自blog.csdn.net/u011214654/article/details/50640601