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
s|áäìú•™º

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

原文地址:https://www.cnblogs.com/luoguoqiang1985/p/3503348.html