• 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简单很多。

  • 相关阅读:
    已经有人提出过循环
    中华术数系列之奇门遁甲精简版
    研究下市场上有哪些软件项目/产品,哪些是值得做的?
    中华术数系列之奇门遁甲手机版
    Webbrowser代理支持
    随笔:杂念纷呈
    架构设计实践:基于WCF大型分布式系统(转)
    WCF分布式开发必备知识(3):Enterpise Services(转)
    看完这20部电影 你能变成经济学大师(转)
    WCF服务契约继承与分解设计(转)
  • 原文地址:https://www.cnblogs.com/luoguoqiang1985/p/3503348.html
Copyright © 2020-2023  润新知