IOS 使用Archive持久化数据

1、持久化一个对象(该对象必须实现NSCoding协议)

主要使用 NSData类中 [ NSMutableData*  writeToFile:path atomically:YES],关键是怎么位data赋值

一下是完整的代码:

储存:

NSString* p = [self getFilePath];  //构建储存路径
    NSLog(@"%@",p);
    
    NSMutableData* data = [[NSMutableData alloc]init];  //构建空数据块(NSMutableData)
    
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]   initForWritingWithMutableData:data];             //创建打包器(NSKeyedArchiver) 与 空数据块(NSMutableData)关联
    
    
    YMPerson *person = [[YMPerson alloc] init];          //构建实际的数据
    person.name = [_et_name text];
    person.age = [_et_age.text intValue];
    person.gender = [_et_set text];
    
    [archiver encodeObject:person];                     //将数据打包到数据块中
    [archiver finishEncoding];
    [data writeToFile:p atomically:YES];                //数据块写到磁盘中


读取:


    NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self getFilePath]];                                 //构建数据储存区块
    NSKeyedUnarchiver*unachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];                  //构建解包器与数据区块关联
    
   YMPerson *person = [unachiver decodeObject];       //读取对象
    
    _et_set.text =person.gender;
    _et_age.text = [NSString stringWithFormat:@"%d",person.age];
    _et_name.text=person.name;
    
    NSLog(@"%@",person);

2.持久化多个对象


写入:

    NSMutableArray* array =[[NSMutableArray alloc] init];  //构建数据储存容器
    
    YMPerson* person1 = [YMPerson initWithName:@"name1" withAge:20 withGender:@"man"];
    YMPerson* person2 = [YMPerson initWithName:@"name2" withAge:22 withGender:@"manman"];
    
    [array addObject:person1];
    [array addObject:person2];  //添加实际储存的数据
    
    [NSKeyedArchiver archiveRootObject:array toFile:[self getFilePath] ];  //写入磁盘


读取:

 NSArray* persons = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath]];
    
    for (YMPerson *p in persons) {
        NSLog(@"%@,%d,%@",p.name,p.age,p.gender);
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值