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.读取出来的数据一定要赋给对象的属性。

 

posted @ 2017-06-26 17:00  蜗牛叔叔  阅读(185)  评论(0编辑  收藏  举报