您的位置:首页 > 产品设计 > UI/UE

UI课程18 初级数据持久化

2015-09-28 20:54 477 查看
1.数据持久化的方式

内存中的数据,程序关闭后会丢失。

1)属性列表(是一种XML文件)

2)NSUserDefault(NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary.)

3)write to file

4)sqlite

5)core data

2.沙盒

1)数据持久化的本质:数据保存成文件,存储到程序的沙盒中。

2)沙盒机制:沙盒的本质就是一个文件夹,名字是随机分配的

3)模拟器路径内有可能包含多个系统版本的路径

4)构成:document、library(cache、preference)、tmp、app程序包

通过代码查找各个文件的相对路径:

NSHomeDirectory()—沙盒主路径

NSDocumentDirectory—documents文件夹

NSLibraryDirectory—Library文件夹

NSCacheDirectory—caches文件夹

NSTemporaryDirectory—tmp文件夹

//获取沙盒主路径
NSString *homePath = NSHomeDirectory();
NSLog(@"%@",homePath);

#pragma mark - objectAtIndex:0、firstObject、lastObject、[0] 使用任意一个都是同一个文件(手机)

//document路径 (通常存放应用程序需要持久化使用的关键数据(用户数据),比如本地数据库等,iTunes在备份的时候会自动备份此文件夹)
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO) objectAtIndex:0];
NSLog(@"%@",documentPath);

//library路径 (通常用来存储应用程序运行期间生成的持久数据,比如用户账户名等。应用程序退出后不会被删除文件夹内数据,但是iTunes备份时,不会备份此文件夹)
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"%@",libraryPath);

//cache路径(运行期间的缓存文件:历史记录等)
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",cachePath);

//preference:应用程序的偏好设置,夜间模式等

//tmp路径(存放临时文件,比如下载的zip包,应用程序结束后被清除)
NSString *tmpPath = NSTemporaryDirectory();
NSLog(@"%@",tmpPath);

//BUndle(当前应用程序包)
//获取当前应用程序包
NSBundle *bundle = [NSBundle mainBundle];
//获取包的路径
//NSString *bundlePath = [bundle resourcePath];
//或者
NSString *bundlePath = [bundle bundlePath];
NSLog(@"%@",bundlePath);

//NSString *image = [bundle pathForResource:@"image" ofType:@"png"];

//    NSString *interfacePath = [bundle pathForResource:@"news" ofType:@"txt"];
//NSLog(@"%@",image);


3.简单对象写入文件(字符串、数组、字典、图片)

1)字符串写入文件

NSString *incantation = @"等闲变却故人心,却道故人心易变";

NSString *path = NSHomeDirectory();
NSLog(@"%@",path);
path = [path stringByAppendingString:@"/纳兰容若.txt"];

//encoding:NSStringEncodingConversionAllowLossy 允许文件丢失
//NSStringEncodingConversionExternalRepresentation 不允许文件丢失
[incantation writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];//(atomically:YES 指的是原子性,和我们声明属性时候的nonatomic非原子性类似的道理,选择YES意思就是说不能被中断,实际操作写入文件的时候,系统会先开辟一个内存空间,将字符串存入这个缓存中,再写入文件,而不是直接写入文件,这样就保证不会出现写入过程中突然中断导致只写入一部分的情况。选择NO即直接写入文件,可以被中断)

//从文件中获取字符串
NSString *resultString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",resultString);


2)数组写入文件

NSArray *array = @[@"相怜相念倍相亲",@"一生一世一双人"];
NSString *path = NSHomeDirectory();
path = [path stringByAppendingPathComponent:@"王安石.txt"];
//写入
[array writeToFile:path atomically:YES];

//读取
NSArray *resultArr = [NSArray arrayWithContentsOfFile:path];
NSLog(@"%@",resultArr[0]);


3)字典写入文件

NSDictionary *dict = @{@"周议":@"宁可我付天下人,不可天下人负我"};
NSString *path = NSHomeDirectory();
path = [path stringByAppendingString:@"/南阳.txt"];
//写入文件
[dict writeToFile:path atomically:YES];

//读取文件
NSDictionary *resultDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"%@",resultDict);


4)图片写入文件(转化成data后写入文件)

UIImage *image = [UIImage imageNamed:@"image"];

//NSData *data = UIImagePNGRepresentation(image);
NSData *data1 = UIImageJPEGRepresentation(image, 1);//“1”表示图片压缩质量(不超过1,越小质量越差)

NSString *path = NSHomeDirectory();
path = [path stringByAppendingString:@"/gir.jpg"];
//写入文件
[data1 writeToFile:path atomically:YES];
//取出
UIImage *resultImg = [UIImage imageWithContentsOfFile:path];
NSLog(@"%@",resultImg);


4.复杂对象写入文件

1)复杂对象即Foundation 框架下不存在的数据类,例如自己创建的类

2)复杂对象至少包含一个实例对象

3)无法在程序内通过writeToFile 类型的方法写入文件中,只能转换为NSData,再通过writeToFile进行数据持久化

4)归档:将复杂对象转换为NSData

反归档:将NSData转换为复杂对象

5)要想写入文件,复杂对象要遵循NSCoding协议,并实现协议方法

6)复杂对象写入的文件在本地打不开

注意:归档和反归档,只是辅助完成数据持久化的功能,本身不能数据持久化

#import "Person.h"

@implementation Person

//编码
- (void)encodeWithCoder:(NSCoder *)aCoder{

[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_gender forKey:@"gender"];

}
//解码
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
_gender = [aDecoder decodeObjectForKey:@"gender"];
}
return self;
}

@end


viewController.m中:

Person *person = [Person new];
person.name = @"Anna";
person.gender = @"male";

NSString *path = NSHomeDirectory();
path = [path stringByAppendingString:@"/person.txt"];//此文件在本地打不开
//对象归档的文件是保密的磁盘上无法查看文件中的内容

//创建可变data,用来存放归档数据
NSMutableData *mutData = [[NSMutableData alloc] initWithCapacity:10];

//创建归档对象
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutData];

//归档
[archiver encodeObject:person forKey:@"person"];
//完成归档
[archiver finishEncoding];
//写入文件
[mutData writeToFile:path atomically:YES];

//使用data对象获取对象
NSData *data = [NSData dataWithContentsOfFile:path];
//创建反归档对象
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//反归档
Person *p = [unarchiver decodeObjectForKey:@"person"];
//完成反归档
[unarchiver finishDecoding];
NSLog(@"%@,%@",p.name,p.gender);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: