美文网首页
数据持久化---序列化存储

数据持久化---序列化存储

作者: 绛紫哟 | 来源:发表于2017-04-27 09:46 被阅读11次

很多情况下,我们都是使用数据库存储数据,但是牵扯到各个model类关联的数据存储时,数据库就有点耗时耗力了,下面我们介绍下序列化存储
1,首先序列化存储的model类需要实现NSCoding协议

#import <Foundation/Foundation.h>

@interface StudentModel : NSObject<NSCoding>

@property (nonatomic,copy) NSString * stu_name;
@property (nonatomic,strong) NSMutableArray * student_likes;

-(id)initWithDic:(NSDictionary *)dic;

#import "StudentModel.h"
#import "LikeModel.h"

@implementation StudentModel

-(id)initWithDic:(NSDictionary *)dic
{
    self = [super init];
    if (self)
    {
        self.stu_name = dic[@"stu_name"];
        for (NSDictionary * likeDic in dic[@"student_likes"])
        {
            LikeModel * likeModel = [[LikeModel alloc]initWithDic:likeDic];
            [self.student_likes addObject:likeModel];
        }
    }
    return self;

}

-(NSMutableArray *)student_likes
{
    if (_student_likes == nil)
    {
        _student_likes = [NSMutableArray array];
    }
    return _student_likes;
}

//对象编码的时候 ,对象的属性会调用这个方法
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_stu_name forKey:@"stu_name"];
    [aCoder encodeObject:_student_likes forKey:@"student_likes"];
}
//对象解码的时候  会调用这个方法
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    
    if (self)
    {
        _stu_name = [aDecoder decodeObjectForKey:@"stu_name"];
        _student_likes = [aDecoder decodeObjectForKey:@"student_likes"];
        

    }
    return self;
}

@end

2,然后就是编码存储数据,解码获取数据

#import "ViewController.h"
#import "JSONKit.h"
#import "StudentModel.h"
#import "LikeModel.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    
    NSArray * strArray = @[@"编码",@"解码"];
    for (int i = 0; i<2; i++)
    {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(100, 100+150*i, 100, 100)];
        [btn setBackgroundColor:[UIColor redColor]];
        [btn setTag:i];
        [btn setTitle:strArray[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickToBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
  
    }
    
    
}
-(void)clickToBtn:(UIButton *)sender
{
    if (sender.tag == 0)
    {
        //获取model(模拟数据)
        NSMutableArray * aa = [NSMutableArray arrayWithObjects:@{@"color":@"222"}, nil];
        NSArray * array = @[@{@"stu_name":@"111",@"student_likes":aa}];
        NSData * jsonData = [array JSONData];
        
        NSArray * studentArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
        
        StudentModel * studentModel = [[StudentModel alloc]initWithDic:studentArr[0]];

        
     //编码
        //实例化一个可变的data
        NSMutableData * data = [[NSMutableData alloc] init];
        //初始化编码类 并且设置data
        NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        [archiver encodeObject:studentModel];
        [archiver finishEncoding];
        BOOL isEncode = [data writeToFile:[self getFilePath:@"123.plist"] atomically:YES];
        NSLog(@"写入%@",isEncode == YES?@"成功":@"失败");
        
    }
    else
    {
    //解码
        
        NSData * data = [NSData dataWithContentsOfFile:[self getFilePath:@"123.plist"]];
        
        NSKeyedUnarchiver * unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        StudentModel * studentModel = [unArchiver decodeObject];
        LikeModel * model = studentModel.student_likes[0];
        [unArchiver finishDecoding];


    }
}
-(NSString *)getFilePath:(NSString *)fileName
{
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:fileName];
    NSLog(@"filePath =====%@",filePath);
    return filePath;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

相关文章

  • java day 19

    持久化和序列化 持久化持久化就是瞬间状态机制转换为持久状态。持久化的主要应用是将内存中的对象存储在数据库中,或者存...

  • IOS开发学习笔记之数据存储

    ++ 数据存储++ios中常用的持久化数据的方法:1、属性列表:Xcode的Property List;再序列化到...

  • iOS-归档NSCoding序列化

    归档 归档->数据持久化的方式->加密(把文件加密《不是把数据加密》 归档分为: 1、存储数据(编码、序列化、归档...

  • java序列化总结

    为什么需要序列化 数据持久化(如session信息存储到redis)或在网络上传输(如RPC远程调用) 序列化要考...

  • php的反序列化利用

    一、简介 为了有效地存储或传递数据,同时不丢失其类型和结构,持久化对象,经常需要利用序列化和反序列化函数对数据进行...

  • 二叉树的序列化与反序列化

    1. 前言:为何要做序列化? 树这种数据结构存在内存中,序列化能够解决机器断电时在持久化存储介质中存储树的结构与数...

  • 数据持久化---序列化存储

    很多情况下,我们都是使用数据库存储数据,但是牵扯到各个model类关联的数据存储时,数据库就有点耗时耗力了,下面我...

  • Java中的序列化与反序列化及xml

    java持久化 是将内存中的对象存储在数据库中,或者存储在磁盘文件中,xml数据文件中。 序列化 将对象的状态信息...

  • iOS归档和解档

    关键词: 归档:数据持久化的一种方式,是将数据进行编码序列化之后存储的过程。适用于小量数据的存储。 解档:对归档的...

  • iOS数据持久化

    Title: iOS数据持久化 ##数据持久化概念 数据持久化就是将内存中的数据模型转换为存储模型,以及将存储模型...

网友评论

      本文标题:数据持久化---序列化存储

      本文链接:https://www.haomeiwen.com/subject/ugdqzttx.html