zoukankan      html  css  js  c++  java
  • NSKeyedArchive(存储自定义对象)

    在viewController.m中:

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        ZWPerson *p = [[ZWPerson alloc] init];
        p.name = @"mc";
        p.age = 18;
        p.height = 1.88;
        NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) lastObject];
        NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
        //拼接路径
        NSString *path = [cache stringByAppendingPathComponent:@"abc.doc"];
        NSString *path1 = [doucument stringByAppendingPathComponent:@"/ce.doc"];
        //存储数据
        BOOL ar = [NSKeyedArchiver archiveRootObject:p toFile:path];
        BOOL ar1 = [NSKeyedArchiver archiveRootObject:p toFile:path1];
        NSLog(@"%d---%d",ar,ar1);
        //读取数据
        ZWPerson *p1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        ZWPerson *p2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path1];
        NSLog(@"%zd---%@",p1.age,p2.name);
    }

    新建ZWPerson类(继承自ViewController)

    在ZWPerson.h中:

    #import "ViewController.h"
    @interface ZWPerson : ViewController
    /** 名字 */
    @property (strong, nonatomic)NSString *name;
    /** 年龄 */
    @property (assign, nonatomic)NSInteger age;
    /** 身高 */
    @property (assign, nonatomic)double height;
    @end

    在ZWPerson.m中:

    #import "ZWPerson.h"
    @interface ZWPerson ()
    @end
    @implementation ZWPerson
    //存储的时候调用这个方法
    - (void)encodeWithCoder:(NSCoder *)aCoder
    {
        //存储对象的属性(根据实际需要存储数据)
        [aCoder encodeObject:self.name forKey:@"name"];
        [aCoder encodeInteger:self.age forKey:@"age"];
        [aCoder encodeDouble:self.height forKey:@"height"];
    }
    //读取的时候调用
    - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        if (self = [super initWithCoder:aDecoder]) {.
            //获取对象的属性(根据实际需要获取数据)
            self.name = [aDecoder decodeObjectForKey:@"name"];
            self.age = [aDecoder decodeIntegerForKey:@"age"];
            self.height = [aDecoder decodeDoubleForKey:@"height"];
        }
        return self;
    }
    @end

    如果是继承自NSObject:则只需要更改initWithCoder中的if(self = super init)即可

    注意:1、遵守NSCoding协议,并实现该协议中的两个方法。

         2、如果是继承,则子类一定要重写那两个方法。因为person的子类在存取的时候,会去子类中去找调用的方法,没找到那么它就去父类中找,所以最后保存和读取的时候新增加的属性会被忽略。需要先调用父类的方法,先初始化父类的,再初始化子类的。

         3、保存数据的文件的后缀名可以随意命名。

         4、通过plist保存的数据是直接显示的,不安全。通过归档方法保存的数据在文件中打开是乱码的,更安全。

  • 相关阅读:
    【其他】UTF-8带签名与不带签名
    【Python】Python 过滤列表
    【EF】EF扩展库(批量操作)
    【python】用 sqlacodegen 将存在的数据库表 转化成model.py
    【python】使用枚举类
    【python】Python: Enum枚举的实现
    【python】python sqlalchemy core
    【python】python字符串前面加u,r,b的含义
    【EF】Entity Framework Core 2.0 特性介绍和使用指南
    Asp.Net 之 前台绑定常用总结
  • 原文地址:https://www.cnblogs.com/jingdizhiwa/p/5644069.html
Copyright © 2011-2022 走看看