测试归档

本文介绍了一种在iOS应用中实现数据持久化的具体方法。通过Objective-C语言演示了如何使用NSKeyedArchiver和NSKeyedUnarchiver来保存和读取自定义对象。文章详细展示了如何将一个自定义的dog类实例存档到文件中,以及从该文件中恢复对象。

#import "ViewController.h"

#import "dog.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

//存数据

- (IBAction)writeDataAction:(UIButton *)sender {

    //1.获取存储的路径

    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    

    NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];

    

    //2.创建对象

    dog *superDog = [[dog  alloc]init];

    superDog.name = @"旺财";

    superDog.age = 18;

    superDog.isTrue = YES;

    

    

    //3.归档  NSKeyedArchive

    //如果使用归档 ,所归档的对象 必须遵守NSCoding 协议, 编码协议

    [NSKeyedArchiver archiveRootObject:superDog toFile:filePath];

    

    

    

  

 

    

    

    

    

     NSLog(@"%@",filePath);

}

 

//读取数据

- (IBAction)readDataAction:(UIButton *)sender {

    

    

 

    //1.获取存储的路径

    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    

    NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];

    

    

    

    //取出存储的对象

    

  dog *superDog =   [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

 

    

    NSLog(@"%@今年%@岁了??? === %@",superDog.name,@(superDog.age),@(superDog.isTrue));

    

   

    

 

}

转载于:https://www.cnblogs.com/dujiahong/p/6431348.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值