关键类:NSKeyedArchiver  与  NSKeyedUnarchiver

采用归档的形式来保存数据,该数据对象需要遵守NSCoding协议,并且该对象对应的类必须提供encodeWithCoder:和initWithCoder:方法。前一个方法告诉系统怎么对对象进行编码,而后一个方法则是告诉系统怎么对对象进行解码

例子:

LQAnimal.h

 #import <UIKit/UIKit.h>

 @interface LQAnimal : NSObject <NSCoding>

 @property (strong) NSString *animalType;

 @end

LQAnimal.m

 #import "LQAnimal.h"

 @implementation LQAnimal

 @synthesize animalType = _animalType;

 /*
*从未归档数据中,初始化对象
*/
- (id) initWithCoder:(NSCoder *) theCoder
{
LQAnimal *what = [[LQAnimal alloc] init]; what.animalType = [theCoder decodeObjectForKey:@"type"]; return what;
} /*
*归档时,编码
*/
- (void) encodeWithCoder:(NSCoder *)theCoder
{
[theCoder encodeObject:self.animalType forKey:@"type"];
} @end
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[];
NSString *detailPath = [NSString stringWithFormat:@"%@/animal.txt",path];
LQAnimal *animal = [[LQAnimal alloc] init];
//animal.animalType = @" little fat sheep ";
animal.animalType = @" big fat sheep ";
BOOL isOK = [NSKeyedArchiver archiveRootObject:animal toFile:detailPath];
if (isOK) {
NSLog(@"save object success!");
LQAnimal *getAnimal = [NSKeyedUnarchiver unarchiveObjectWithFile:detailPath];
NSLog(@"APP get animal type:%@", getAnimal.animalType);
} else{
NSLog(@"save object fail!");
}

执行结果:

2014-01-03 19:12:22.144 Objc[696:c07] save object success!
2014-01-03 19:12:25.601 Objc[696:c07] APP get animal type: big fat sheep

我执行后,也检查过了animal.txt文本内容,发现系乱码。。

bplist00‘T$topX$objectsX$versionY$archiver—Trootħ
U$null“
V$classTtypeÄÄ_ big fat sheep “X$classesZ$classname¢XLQAnimalXNSObjectXLQAnimal܆_NSKeyedArchiver(:<AGLSXZ\ns|áäìú•™º

这种模式只适合少量配置数据的存储。优点就系够简单。起码比sqlite简单很多。

最新文章

  1. iOS - 静态库的创建与使用
  2. Deadlock Detecting--转
  3. IE里面的一些BUG记录
  4. iOS Library not loaded: Reason: image not found
  5. MVVM架构~前台后台分离的思想与实践
  6. 2015baidu复赛2 连接的管道(mst &amp;&amp; 优先队列prim)
  7. Android系统自带样式(@android:style/) (转)
  8. Shell的概念
  9. ***ECharts图表入门和最佳实践
  10. http://nxlhero.blog.51cto.com/962631/1666250?plg_nld=1&amp;plg_uin=1&amp;plg_auth=1&amp;plg_nld=1&amp;plg_usr=1&amp;plg_vkey=1&amp;plg_dev=1
  11. 批量将MP4 转换为 MP3
  12. IO 流—&gt;&gt;&gt;补充
  13. ios页面跳转
  14. ssh相关命令
  15. Linux中Nginx反向代理下的tomcat集群
  16. 前端构建之gulp与常用插件(转载)
  17. 使用HttpClient进行https连接(一)
  18. spring学习(二) ———— AOP之AspectJ框架的使用
  19. css制作表格
  20. 用Jquery获取checkbox多个选项

热门文章

  1. android camera(一):camera模组CMM介绍
  2. 一个简单的DELPHI程序注册码设计 .
  3. php中数组可以不写下标
  4. hbulider 快捷键以及常用
  5. C的printf与scanf的用法
  6. Chrome/Chromium HTML5 video 视频播放硬件加速
  7. FastDFS 的部署、配置与测试的
  8. [ES7] Exploring ES2016 Decorators
  9. Cocos2d-x在win32,android和IOS下的文件读写问题
  10. android智能天气闹钟应用开发经过