您的位置:首页 > 移动开发 > Objective-C

【Objective-C基础】数据持久化--对象归档

2016-06-30 10:12 309 查看
原文:http://www.2cto.com/kf/201310/248330.html

一、数据持久化的方式
1、NSKeyedArchiver--对象归档
2、属性列表化(NSArray、NSDictionary、NSUserDefault)
3、SQlite数据库、CoreData数据库
 其中第一、二种方式针对数据量小的数据,第三种方式针对大数据,归档的文件是加密的,属性列表明文的。
 归档的形式;
 A、对foundation库中对象进行归档
 B、自定义对象的归档(需要实现归档协议: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!");  

更多内容请参考《【Objective-C基础】自定义对象归档
结束!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: