zoukankan      html  css  js  c++  java
  • 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

    运行结果:

  • 相关阅读:
    DM9000网卡驱动接受数据从中断方式改成NAPI方式小记
    20130317
    c++版本新浪微博sdk库交叉编译
    新年预期小记
    arm+linux嵌入式系统的终端显示中文乱码解决
    记transmission下载sd卡支持不佳问题
    嵌入式linux自动登录
    SevenArmsSeries.Repositories
    Mybatis开启二级缓存(全局缓存)的方法
    Spring学习之动态代理的简单实现
  • 原文地址:https://www.cnblogs.com/qianLL/p/5302910.html
Copyright © 2011-2022 走看看