zoukankan      html  css  js  c++  java
  • IOS 数据存储(NSKeyedArchiver 归档篇)

    什么是归档

    当遇到有结构有组织的数据时,比如字典,数组,自定义的对象等在存储时需要转换为字节流NSData类型数据,再通过写入文件来进行存储。

    归档的作用

    之前将数据存储到本地,只能是字符串、数组、字典、NSNuber、BOOL等容器类对象,不能将自定义对象进行保存,而通过归档能将所有的对象转化为二进制数据存储到文件中。

    归档的缺点

    归档保存数据,只能一次性归档保存以及一次性解压。所以只能针对小量数据,而且对数据操作比较笨拙,即如果想改动数据的某一小部分,还是需要解压整个数据或者归档整个数据。

    归档的使用场景

    1.有些应用支持一个离线缓存,也就是说当手机没联网时,可以将手机有网时的数据存放在本地,当手机没网时,从本地中取出来这些数据展示。

    2.电商场景中,可以缓存用户搜索历史记录。

    归档的三种方式

    1.对Foundation框架的系统对象进行归档
    2.对自定义的对象进行归档
    3.同时对不同类型的多个对象进行归档

    //将数据对象归档到指定目录
    + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
    

     这个方法可以对基本数据类型进行归档,比如字符串,NSNumber,常用的是对NSArray、NSDictionary进行归档。返回值标志着是否归档成功,YES为成功,NO为失败。

    //通过文件路径创建解归档对象
    + (nullable id)unarchiveObjectWithFile:(NSString *)path;

    使用例子

    归档

    NSDictionary *personDict=@{@"name":@"xiaoBai",@"age":@"25",@"sex":@"man"};
    NSArray *array = @[@"数据1",@"数据2",@"数据3",@"数据4"];
    
    //获取沙盒中Documents的路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    
    //设置对象归档的路径及归档文件名
    NSString *dictPath =[docPath stringByAppendingPathComponent:@"person.archiver"];//后缀名可以随意命名
    
    //将对象归档到指定路径
    BOOL flag1 = [NSKeyedArchiver archiveRootObject:array toFile:dictPath];
    
    NSString *arrayPath =[docPath stringByAppendingPathComponent:@"data.archiver"];
    BOOL flag2 = [NSKeyedArchiver archiveRootObject:dic toFile:arrayPath];

    反归档

    //获取沙盒中Documents的路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    
    //设置对象归档的路径及归档文件名
    NSString *dictPath =[docPath stringByAppendingPathComponent:@"person.archiver"];//后缀名可以随意命名
    
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:dictPath];
    
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:arrayPath];

    2.对自定义的对象进行归档

    除了字典和数组等系统对象外,开发中往往需要自定义一些对象,如:定义一个person类。

    person.h

    #import <Foundation/Foundation.h>
    
    // 归档自定义对象该对象必须实现nscoding 协议
    @interface person : NSObject<NSCoding>
    
    @property (nonatomic,copy) NSString *name;
    @property (nonatomic,assign) NSInteger age;
    @property (nonatomic,assign) double height;
    
    @end

    person.m

    需要重写两个协议方法

    -(void)encodeWithCoder:(NSCoder *)aCoder方法:
    -(id)initWithCoder:(NSCoder *)aDecoder方法:

    #import "person.h"
    
    @implementation person
    
    // 当将一个自定义对象保存到文件的时候就会调用该方法
    // 在该方法中说明如何存储自定义对象的属性
    // 也就说在该方法中说清楚存储自定义对象的哪些属性
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
             NSLog(@"调用了encodeWithCoder:方法");
             [aCoder encodeObject:self.name forKey:@"name"];
             [aCoder encodeInteger:self.age forKey:@"age"];
             [aCoder encodeDouble:self.height forKey:@"height"];
    }
    
    // 当从文件中读取一个对象的时候就会调用该方法
    // 在该方法中说明如何读取保存在文件中的对象
    // 也就是说在该方法中说清楚怎么读取文件中的对象
    -(id)initWithCoder:(NSCoder *)aDecoder
    {
         NSLog(@"调用了initWithCoder:方法");
         //注意:在构造方法中需要先初始化父类的方法
         if (self=[super init]) {
                 self.name=[aDecoder decodeObjectForKey:@"name"];
                 self.age=[aDecoder decodeIntegerForKey:@"age"];
                 self.height=[aDecoder decodeDoubleForKey:@"height"];
             }
         return self;
     }
    
    @end

    对person对象进行归档

    - (void)archiveObjectAction{
        person *xiaoBai = [[person alloc] init];
        xiaoBai.name = @"小白";
        xiaoBai.age = 25;
        xiaoBai.height = 180;
        // 获取文件路径
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [docPath stringByAppendingPathComponent:@"person.archiver"];
        
        // 保存自定义对象
        [NSKeyedArchiver archiveRootObject:xiaoBai toFile:path];
    }
    - (void)unarchiveOjectAction{
            // 获取文件路径
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [docPath stringByAppendingPathComponent:@"person.archiver"];
        
        person *personObj = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"%@,%d,%.1fcm",personObj.name,personObj.age,personObj.height);
    }

    3.同时对不同类型的多个对象进行归档

    方法介绍

    //对多个对象进行归档(可以是不同类型的对象)
    - (instancetype)initForWritingWithMutableData:(NSMutableData *)data;

    归档:

    // NSKeyedArchiver 可以对多种类型数据进行归档
    CGPoint point = CGPointMake(10, 20);
    NSString *name = @"xiaoBai";
    NSInteger age = 25;
    
    //获取沙盒中Documents的路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    
    //指定归档路径
    NSString *path = [docPath stringByAppendingPathComponent:@"multiData.archiver"];
    
    //实例化归档对象
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    //将对象进行编码(将数据对象转换为字节流数据)
    [archvier encodeCGPoint:point forKey:@"point"];
    [archvier encodeObject:name forKey:@"name"];
    [archvier encodeInteger:age forKey:@"age"];
    
    //结束编码
    [archvier finishEncoding];
    
    //将字节流写入指定路径的文件
    [data writeToFile:path atomically:YES];
    //获取沙盒中Documents的路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    
    //指定归档路径
    NSString *path = [docPath stringByAppendingPathComponent:@"multiData.archiver"];
    
    //实例化反归档对象
    NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    
    //解码(将字节流转换为数据对象)
    CGPoint pointR = [unarchiver decodeCGPointForKey:@"point"];
    NSString *nameR = [unarchiver decodeObjectForKey:@"name"];
    NSInteger ageR = [unarchiver decodeIntegerForKey:@"age"];
    
    //结束解码
    [unarchiver finishDecoding];
    NSLog(@"%f,%f,%@,%d",pointR.x,pointR.y,nameR,ageR);
  • 相关阅读:
    集合中的3个经典练习题
    创建泛类集合List以及数组转集合,集合转数组的应用
    添加一个txt文件(例如在桌面),利用后台对文件写入内容
    File类的创建,删除文件
    集合中存放随机数的问题之解析
    集合中的类型转化 以及求集合中元素的最大值,平均值
    response.sendRedirect()使用注意事项
    request.getContextPath是为了解决相对路径的问题,可返回站点的根路径
    java中instanceof的用法
    getParameter 与 getAttribute的区别
  • 原文地址:https://www.cnblogs.com/fengfeng159/p/11057820.html
Copyright © 2011-2022 走看看