zoukankan      html  css  js  c++  java
  • iOS数据持久化--归档

    一、简介

      在使用plist进行数据存储和读取,只适用于系统自带的一些常用类型才能用,且必须先获取路径相对麻烦;

      偏好设置(将所有的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息

      归档:因为前两者都有一个致命的缺陷,只能存储常用的类型。归档可以实现把自定义的对象存放在文件中。

    二、使用

    #import "ViewController.h"
    #import "Person.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        //1.创建对象
        Person *p=[[Person alloc]init];
        p.name=@"deng";
        p.age=23;
        p.height=1.7;
    
        //2.获取文件路径
        NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        NSString *path=[docPath stringByAppendingPathComponent:@"person.deng"];
        NSLog(@"path=%@",path);
        
        //3.将自定义的对象保存到文件中
        [NSKeyedArchiver archiveRootObject:p toFile:path];
    }
    
    
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        
        //1.获取文件路径
        NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        NSString *path=[docPath stringByAppendingPathComponent:@"person.deng"];
        NSLog(@"path=%@",path);
         //2.从文件中读取对象
         Person *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
         NSLog(@"%@,%d,%.1f",p.name,p.age,p.height);
    }
    @end

    person.h文件

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject <NSCoding>
    
    @property(nonatomic,strong)NSString *name;
    @property(nonatomic,assign)int age;
    @property(nonatomic,assign)double height;
    
    
    @end

    person.m

    #import "Person.h"
    
    @implementation Person
    
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [aCoder encodeObject:self.name forKey:@"name"];
        [aCoder encodeInt:self.age forKey:@"age"];
        [aCoder encodeDouble:self.height forKey:@"height"];
    }
    
     -(id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self == [super init]) {
           self.name = [aDecoder decodeObjectForKey:@"name"];
           self.age = [aDecoder decodeIntForKey:@"age"];
           self.height = [aDecoder decodeDoubleForKey:@"height"];
        }
        return self;
    }
    
    @end

    三、注意

    1.一定要实现协议<NSCoding>,并在要保存对象的.m文件中实现两个协议方法(如果不实现会报错):

      -(void)encodeWithCoder:(NSCoder *)aCoder

       -(id)initWithCoder:(NSCoder *)aDecoder

    2.保存保存时对象的属性类型一定要注意,要用对应的方法保存对应的属性。

    3.读取出来的数据一定要赋给对象的属性。

  • 相关阅读:
    485串口接线
    mvc3 升级mvc5
    VB连接ACCESS数据库,使用 LIKE 通配符问题
    VB6 读写西门子PLC
    可用的 .net core 支持 RSA 私钥加密工具类
    解决 Win7 远程桌面 已停止工作的问题
    解决 WinForm 重写 CreateParams 隐藏窗口以后的显示问题
    解决安装 .net framework 发生 extracting files error 问题
    CentOS7 安装配置笔记
    通过特殊处理 Resize 事件解决 WinForm 加载时闪烁问题的一个方法
  • 原文地址:https://www.cnblogs.com/huadeng/p/7081359.html
Copyright © 2011-2022 走看看