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

  • 相关阅读:
    AngularJs 与Jquery的对比分析,超详细!
    身份证号验证,获取户口地址、性别、出生日期
    前端面试·
    页面可见性(Page Visibility API) 可以有哪些用途?
    webSocket如何兼容低浏览器?(阿里)
    如何实现浏览器内多个标签页之间的通信?
    HTML5的form如何关闭自动完成功能?
    Label的作用是什么?是怎么用的?
    cookies,sessionStorage 和 localStorage 的区别?
    浏览器是怎么对HTML5的离线储存资源进行管理和加载的呢?
  • 原文地址:https://www.cnblogs.com/luoguoqiang1985/p/3503348.html
Copyright © 2011-2022 走看看