ios专题 -归档保存数据

关键类:NSKeyedArchiver  与  NSKeyedUnarchiver

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

例子:

LQAnimal.h

 

1 #import <UIKit/UIKit.h>
2 
3 @interface LQAnimal : NSObject <NSCoding>
4 
5 @property (strong) NSString *animalType;
6 
7 @end

 

LQAnimal.m

复制代码
 1 #import "LQAnimal.h"
 2 
 3 @implementation LQAnimal
 4 
 5 @synthesize animalType = _animalType;
 6 
 7 /*
 8  *从未归档数据中,初始化对象
 9  */
10 - (id) initWithCoder:(NSCoder *) theCoder
11 {
12     LQAnimal *what = [[LQAnimal alloc] init];
13     
14     what.animalType = [theCoder decodeObjectForKey:@"type"];
15     
16     return what;
17 }
18 
19 /*
20  *归档时,编码
21  */
22 - (void) encodeWithCoder:(NSCoder *)theCoder
23 {
24     [theCoder encodeObject:self.animalType forKey:@"type"];
25 }
26 
27 @end
复制代码
复制代码
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
    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(25:<AGLSXZ\ns|áäìú•™º

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

 

 

 

posted @   路途遥远  阅读(307)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示