zoukankan      html  css  js  c++  java
  • 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简单很多。

  • 相关阅读:
    做足以让自己骄傲的活
    Count(*) 与 count(field) 一样吗?
    Explain Plan试分析
    Oracle SQL Developer中查看解释计划Explain Plan的两种方法
    整理+学习《骆昊-Java面试题全集(上)》
    【转】Java就业指导
    如何清晰的、高质量的给面试官介绍自己的电商项目【借鉴】
    留存的图片
    Linux学习_006_JavaEE程序员常用linux命令整理
    给Linux初学者的七个建议,值得一读
  • 原文地址:https://www.cnblogs.com/luoguoqiang1985/p/3503348.html
Copyright © 2011-2022 走看看