• iOS 自定义的对象类型的解档和归档


    自定义的对象的解档和归档

     


    如果想对自己自定义的类进行解档和归档的话 必须遵循一个协议:NSCoding

    Student.h 文件

    #import <Foundation/Foundation.h>
    
    @interface Student : NSObject<NSCoding>
    @property(nonatomic,strong)NSString *name;
    @property(nonatomic,assign)int age;
    
    -(instancetype)initWithName:(NSString *)name AndAge:(int)age;
    
    @end

    Student.m 文件

    #import "Student.h"
    
    @implementation Student
    
    
    - (instancetype)initWithName:(NSString *)name AndAge:(int)age
    {
        self = [super init];
        if (self) {
            _age=age;
            _name=name;
        }
        return self;
    }
    //解答时候调用 是一个初始化的方法
    -(instancetype)initWithCoder:(NSCoder *)aDecoder{
    
        self=[super init];
        if (self) {
            _name=[aDecoder decodeObjectForKey:@"name"];
            _age=(int)[aDecoder decodeIntegerForKey:@"age"];
        }
        return self;
    }
    
    //归档调用该方法
    -(void)encodeWithCoder:(NSCoder *)aCoder{
    
        NSLog(@"encodeWithCoder");
        [aCoder encodeObject:_name forKey:@"name"];
        [aCoder encodeInteger:_age forKey:@"age"];
        
    }
    
    -(NSString *)description{
        return [NSString stringWithFormat:@"name=%@,age=%d",_name,_age];
    }
    
    
    @end

    客户端代码

    #import "ViewController.h"
    #import "Student.h"
    #define PATH [NSHomeDirectory() stringByAppendingPathComponent:@"Student.qll"]
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        NSLog(@"%@",PATH);
        
        Student *stu=[[Student alloc]init];
        stu.name=@"张F";
        stu.age=13;
    
        NSLog(@"%@",stu);
        //归档
      BOOL bol=[NSKeyedArchiver archiveRootObject:stu toFile:PATH];
        
        if (bol==1) {
            NSLog(@"归档成功");
        }
    
        //解档
        
        Student *stu1=[NSKeyedUnarchiver unarchiveObjectWithFile:PATH];
        NSLog(@"%@",stu1);
    
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end

    运行结果:

  • 相关阅读:
    Github访问失败如何解决
    持续交付发布可靠软件的系统方法
    windows上tomcat部署
    软件测试总结
    CentOS cannot find a valid baseurl for repo base/7/x86_64
    姜碧野写给纪中信息学学弟学妹的信
    2022 纪中集训 7.6
    2022 纪中集训7.7
    2022 纪中集训 7.8
    2022 纪中集训 7.11 笔记
  • 原文地址:https://www.cnblogs.com/qianLL/p/5302910.html
Copyright © 2020-2023  润新知