zoukankan      html  css  js  c++  java
  • 自定义类归档

    自定义类如果需要归档的话,需要遵守NSCoding协议,并实现两个方法:

    - (void)encodeWithCoder:(NSCoder *)aCoder;
    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;

    下面以自定义 Person 类为例:

    //.h文件
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject <NSCoding>
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, assign) NSUInteger age;
    @end
    
    //.m文件
    #import "Person.h"
    
    @implementation Person
    
    /** 
      数据归档调用
        (1)那些属性需要归档
        (2)这些属性如何归档
     */
    - (void)encodeWithCoder:(NSCoder *)aCoder{
        [aCoder encodeObject:self.name forKey:@"name"];
        [aCoder encodeInteger:self.age forKey:@"age"];
    }
    
    /** 
     数据解档调用 
        (1)那些属性需要解档
        (2)如何解档
     */
    - (instancetype)initWithCoder:(NSCoder *)aDecoder{
        //当父类中又 NSCoding 协议的时候,用[super initWithCoder:aDecoder];
        self = [super init];
        if (self) {
            _name = [aDecoder decodeObjectForKey:@"name"];
            _age = [aDecoder decodeIntegerForKey:@"age"];
        }
        return self;
    }
    
    //类似于java的toString方法
    - (NSString *)description{
       return [NSString stringWithFormat:@"name: %@, age: %zd", self.name, self.age];
    }
    
    @end

    主文件main.m

    //初始化自定义类
            Person *person = [[Person alloc] init];
            person.name = @"张三";
            person.age = 20;
    
            //获取存储路径
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSString *filePath = [cachesPath stringByAppendingPathComponent:@"person.data"];
            //数据归档
            [NSKeyedArchiver archiveRootObject:person toFile:filePath];
            //数据解档
            Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            NSLog(@"%@",p);
    

    最终的结果为:
    test[8814:79293] name: 张三, age: 20

    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    [模板] 循环数组的最大子段和
    [最短路][几何][牛客] [国庆集训派对1]-L-New Game
    [洛谷] P1866 编号
    1115 Counting Nodes in a BST (30 分)
    1106 Lowest Price in Supply Chain (25 分)
    1094 The Largest Generation (25 分)
    1090 Highest Price in Supply Chain (25 分)
    树的遍历
    1086 Tree Traversals Again (25 分)
    1079 Total Sales of Supply Chain (25 分 树
  • 原文地址:https://www.cnblogs.com/xiaocai-ios/p/7779783.html
Copyright © 2011-2022 走看看