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

本文介绍如何使用NSCoding协议实现自定义对象的解档和归档功能,通过实例展示如何在Objective-C中操作自定义类的数据持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 


如果想对自己自定义的类进行解档和归档的话 必须遵循一个协议: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

运行结果:

 

转载于:https://www.cnblogs.com/qianLL/p/5302910.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值