自定义对象归档(解档)

首先自定义一个Person对象
person.h里的内容 (注意要遵守NSCoding协议)

@interface Person : NSObject <NSCoding>

@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) NSUInteger age;

@end

Person.m里要实现归档、解档的方法

@implementation Person

// 在对象归档的时候调用
// 那些属性需要归档
// 这些属性怎么归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
}

// 在对象解档的时候调用
// 哪些属性需要解档
// 这些属性怎么解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {

        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeIntegerForKey:@"age"];

    }
    return self;
}
@end

在SB中设置两个Button,存储和读取。然后在ViewController.m中实现它们的点击事件

- (IBAction)save:(UIButton *)sender
{
    // 定义一个Person对象
    Person *p1 = [[Person alloc] init];
    p1.name = @"zhansan";
    p1.age = 20;

    // 获得Cache的路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    // 拼接文件路径
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"person.data"];

    // 归档Person对象
    [NSKeyedArchiver archiveRootObject:p1 toFile:filePath];


}
- (IBAction)read:(UIButton *)sender
{
    // 获得Cache的路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    // 拼接文件路径
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"person.data"];

    // 解档Person对象
    Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    NSLog(@"%@",p.name);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值