zoukankan      html  css  js  c++  java
  • 编码和解码(序列化和反序列化)

    cocoa具备一种机制来将自定义对象自身转换为某种格式并保存中磁盘上。

    对象可以将它的实例变量和其它数据编码为数据块,然后保存到磁盘中(编码)。以后将这些数据块加载到内存中,并且

    还能基于保存的数据创建新对象。这个过程称为编码和解码,或称为序列化和反序列化。

    DOC:The init method that gets used depends on how the view is created. It can be explicitly created using initWithFrame or it can be created by loading a nib. In that case, the initWithCoder method gets called when the view is loaded from the nib. There are other init methods for subclasses (like UITableViewController has initWithStyle), so you have to be sure which one is being called.

    要实现对象的编解码,必须实现NSCoding协议。

    @protocol NSCoding

    -(void) encoderWithCoder:(NSCoder *) aCoder;//对象保存自身时--编码

    -(id) initWithCoder:(NSCoder *) aDecoder;//对象加载自身时--解码

    @end

    //nscoding协议的编码方法

    -(void) encodeWithCoder:(NSCoder *) coder{

    [coder encodeObject:name forKey:@"name"];

    [coder encodeInt:magicNumber forKey:@"magicNumber"];

    [coder encodeFloat:shoseSize forKey:@"shoseSize"];

    [coder encodeObject:subThingies forKey:@"subThingies"];

    }

    //解码

    initWithCode:和其他init方法一样,在对对象执行操作之前,需要使用超类对它们进行初始化。为此,可以采用

    两种方式,具体取决于父类,如果父类采用了NSCoding协议,则应该调用[super initWithCoder:decoder];

    否则,只需要调用[super init]即可。NSObject不采用NSCoding协议,因此我们可以使用简单的init方法。

    -(id) initWithCoder:(NSCoder *)  decoder{

    if(self =[super init]){

    self.name=[decoder decodeObjectForKey:@"name"];

    self.magicNumber=[decoder decodeIntForKey:@"magicNumber"];

    self.shoseSize=[decoder decodeFloatForKey:@"shoseSize"];

    self.subThingies=[decoder decodeObjectForKey:@"subThingies"];

    }

    return (self);

    }

     附加:http://blog.csdn.net/itianyi/article/details/8917026

     
     
  • 相关阅读:
    对Linux内核中进程上下文和中断上下文的理解
    深入浅出进程与线程的基本概念
    真正明白c语言二级指针
    寄存器变量
    python类中初始化为可变对象的属性,在多次对类实例化时数据会堆叠
    python中使用uwsgi启动wsgi应用
    火狐新版移除developer Toolbar和无法关闭自动更新的解决
    hive中计算某个日期是星期几的算法
    计算两个日期之间的天数(去掉周六周日)
    hive动态分区常用参数
  • 原文地址:https://www.cnblogs.com/liuziyu/p/4182520.html
Copyright © 2011-2022 走看看