第一、数据持久化的方式:
NSKeyedArchiver--对象归档
属性列表化(NSArray、NSDictionary、NSUserDefault)
SQlite数据库、CoreData数据库
其中第一、二种方式针对数据量小的数据,第三种方式针对大数据,归档的文件是加密的,属性列表明文的。
归档的形式;
对foundation库中对象进行归档
自定义对象的归档(需要实现归档协议:NSCoding)
第二 最简单归档和解归档的实现代码:
@autoreleasepool {
NSString *homeDictory=NSHomeDirectory();
NSArray *array=[NSArray arrayWithObjects:@"one",@"two",@"three",nil];
NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/test.archive"];
if(![NSKeyedArchiver archiveRootObject:array toFile:homePath])
{
NSLog(@"归档失败");
}else
{
NSArray *data=[NSKeyedUnarchiver unarchiveObjectWithFile:homePath];
NSLog(@"%@",data);
}
NSLog(@"Hello, World!");
}
第四、复杂的内容归档
使用NSData实例作为归档的存储数据,添加归档的内容(设置key和value),完成归档,将归档内容存入磁盘
解归档步骤:从磁盘读取文件,生成NSData实例,根据data实例创建或初始化归档实例,解归档,根据key访问value的值
NSString *homeDictory=NSHomeDirectory();
NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/usertest.archive"];
NSMutableData *data=[NSMutableData data];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
NSArray *nameArray=[NSArray arrayWithObjects:@"andy",@"yang", nil];
[archiver encodeInt:100 forKey:@"age"];
[archiver encodeObject:nameArray forKey:@"names"];
[archiver finishEncoding];
[archiver release];
if ([data writeToFile:homePath atomically:YES])
{
NSData *data2=[NSData dataWithContentsOfFile:homePath];
NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data2];
int age=[unarchiver decodeIntForKey:@"age"];
NSArray *array2=[unarchiver decodeObjectForKey:@"names"];
NSLog(@"%d",age);
NSLog(@"%@",array2);
[unarchiver release];
} else
{
NSLog(@"write to file wrong");
}
NSLog(@"Hello, World!");
}