zoukankan      html  css  js  c++  java
  • iOS 中实现 快速归档 与 快速解档


    1
    //解档 2 - (id)initWithCoder:(NSCoder *)decoder 3 { 4 if (self = [super init]) { 5 unsigned int count = 0; 6 //获取类中所有成员变量名 7 Ivar *ivar = class_copyIvarList([self class], &count); 8 for (int i = 0; i<count; i++) { 9 Ivar iva = ivar[i]; 10 const char *name = ivar_getName(iva); 11 NSString *strName = [NSString stringWithUTF8String:name]; 12 //进行解档取值 13 id value = [decoder decodeObjectForKey:strName]; 14 //利用KVC对属性赋值 15 [self setValue:value forKey:strName]; 16 } 17 free(ivar); 18 } 19 return self; 20 }
     1 //归档
     2 - (void)encodeWithCoder:(NSCoder *)encoder
     3 {
     4     unsigned int count;
     5     Ivar *ivar = class_copyIvarList([self class], &count);
     6     for (int i=0; i<count; i++) {
     7         Ivar iv = ivar[i];
     8         const char *name = ivar_getName(iv);
     9         NSString *strName = [NSString stringWithUTF8String:name];
    10         //利用KVC取值
    11         id value = [self valueForKey:strName];
    12         [encoder encodeObject:value forKey:strName];
    13     }
    14     free(ivar);
    15 }

    大家在做归档与解档的时候,都需要在要归档的自定义类中服从<NSCoding>协议,并实现对应的每个方法,并在方法中对每个属性进行大部分代码的编写,但是现在只需要赋值上文中的两端代码就OK了

  • 相关阅读:
    二级联动
    ajax的post请求方式
    ajax基本常识及get请求方式
    google-gson库下的gson的基本使用
    org.json库下的json的基本使用
    初步认识session
    JSTL的基本使用
    EL的基本使用
    jsp编译器指令errorPage的用法
    poj 1742(好题,楼天城男人八题,混合背包)
  • 原文地址:https://www.cnblogs.com/PSSSCode/p/5479472.html
Copyright © 2011-2022 走看看