zoukankan      html  css  js  c++  java
  • iOS Swift3.0 OC 数据储存--归档

    一、Swift 3.0

    1、model

    class userModel: NSObject,NSCoding {
        
        var account: String = ""
        var regmobile: String = ""
        var sec1_question: String = ""
    
        
        
        func encode(with aCoder: NSCoder) {
            aCoder.encode(account, forKey:"account")
            aCoder.encode(regmobile, forKey:"regmobile")
            aCoder.encode(sec1_question, forKey:"sec1_question")
            aCoder.encode(expert_audit, forKey:"expert_audit")
         
        }
        
        
        required init?(coder aDecoder: NSCoder) {
            super.init()
            account = (aDecoder.decodeObject(forKey:"account")as? String)!   
            status = (aDecoder.decodeObject(forKey:"status")as? String)!
            nickname = (aDecoder.decodeObject(forKey:"nickname")as? String)!
            
    
        }
      
    }
    View Code

    2、 归解档

      //  路径:
    let userAccountPath = "(NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!)/southDream.data"
    
    
    
    
      //归档
                NSKeyedArchiver.archiveRootObject(model, toFile: userAccountPath + "/userModel")
    
    
    //解档
                if NSKeyedUnarchiver.unarchiveObject(withFile: userAccountPath) != nil {
                    
                  let  model = NSKeyedUnarchiver.unarchiveObject(withFile: userAccountPath) as? userModel
                }
    View Code

    二、OC

    四种数据持久化方式 http://www.cocoachina.com/ios/20160617/16739.html 

    //

    //归档数据,并用二进制写入文件  
    NSMutableData *data = [NSMutableData data];  
    NSKeyedArchiver *keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];  
    [keyedArchiver encodeObject:Users forKey:@"users"];//Users已知的保存用户信息的数组  
    [keyedArchiver finishEncoding];  
    [data writeToFile:@"归档数据保存路径" atomically:YES];  
    [objc] view plain copy print?
    //读取上面已经保存好的文件,并反归档后在程序中使用数据  
    NSData *newData = [NSData dataWithContentsOfFile:@"归档数据保存路径"];  
    NSKeyedUnarchiver *keyedUnArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:newData];  
    NSArray *users = [keyedUnArchiver decodeObjectForKey:@"users"];  
    for (User *user in users) {  
        NSLog(@"name = %@  pw = %@",u.name,u.password);  
    }  
    
    注意:需要归档的数据中如果含有自定义的对象,那么该对象需遵守<NSCoding>协议,并重写如下方法:
    [objc] view plain copy print?
    - (void)encodeWithCoder:(NSCoder *)aCoder{  
        [aCoder encodeObject:对象属性 forKey:@"归档的key"];  
    }  
    [objc] view plain copy print?
    - (id)initWithCoder:(NSCoder *)aDecoder{  
        self = [super init];  
        if (self) {  
            实例变量 = [aDecoder decodeObjectForKey:@"归档的key"];  
        }  
        return self;  
    }  
    用法扯皮

    //先把数据在model中归解档

    。h

    @property(nonatomic,copy)NSString *email;
    @property(nonatomic,copy)NSString *uid;
    @property(nonatomic,copy)NSString *mobile;
    View Code

    *is_sec_pwd;

    。m

    #import "UserModel.h"
    static UserModel *model;
    @implementation UserModel
    +(UserModel *)defaultCellModel{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (!model) {
                model = [[UserModel alloc]init];
            }
        });
        return model;
    }
    - (void)encodeWithCoder:(NSCoder *)aCoder{
        [aCoder encodeObject:self.account forKey:@"account"];
        [aCoder encodeObject:self.regmobile forKey:@"regmobile"];
        [aCoder encodeObject:self.sec1_question forKey:@"sec1_question"];
    
      
        
    }
    
    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
        self = [super init];
        
        if(self)
            
        {
            
            self.account = [aDecoder decodeObjectForKey:@"account"];
            
            self.regmobile = [aDecoder decodeObjectForKey:@"regmobile"];
            self.sec1_question = [aDecoder decodeObjectForKey:@"sec1_question"];
            self.headimage = [aDecoder decodeObjectForKey:@"headimage"];
       
            
        }
        
        return self;
    
    }
    
    @end
    View Code

    NSUserDefaults

     保存

    Model数据-》归档-》NSUserdefaults 

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    //不能直接存取NSObject,需要先归档转成NSData

    NSData  *data  = [NSKeyedArchiver archivedDataWithRootObject:model];             

     [defaults setObject:data forKey:@"model"];

    NSUserdefaults-》解档-》Model数据

    NSData *modeldata = [[NSUserDefaults standardUserDefaults]objectForKey:@"model"];

     usermodel = [NSKeyedUnarchiver unarchiveObjectWithData:modeldata];

     

    //文件中保存

    #import "ViewController.h"
    #import "linePesist.h"
    //导入数据模型类
    #define CodeString  @"CodeString"
    @implementation ViewController
    -(NSString *)dataFile{
    NSArray *ar = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *fielpath = [ar objectAtIndex:0];
    return [fielpath stringByAppendingPathComponent:@"data.archive"];
    //改修后缀名,以免与属性列表创建的文件重复,而加载成旧的的文件。 不用查字典了。。archive表归档
    }
    - (void)viewDidLoad {
    [super viewDidLoad];
    NSString *filepath = [self dataFile];
    NSLog(@"%@",filepath);
    if([[NSFileManager defaultManager]fileExistsAtPath:filepath]) {
    //创建2个实例
    NSData *data = [[NSData alloc]initWithContentsOfFile:filepath]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    //把已归档的对象读取。赋值给linepesist
    linePesist *linepesist =[unarchiver decodeObjectForKey:CodeString]; [unarchiver finishDecoding];
    //完成解档
    for(int i = 0;i
  • 相关阅读:
    Java高级面试题及答案
    Java SQL注入学习笔记
    Java实习生面试题整理
    各大公司Java面试题超详细总结
    Java面试经典题:线程池专题
    Java进阶面试题列表
    最新Java面试题及答案整理
    Java虚拟机(JVM)你只要看这一篇就够了!
    记一次Java的内存泄露分析
    Java线程池详解
  • 原文地址:https://www.cnblogs.com/xujiahui/p/6882009.html
Copyright © 2011-2022 走看看