美文网首页
存储用法之NSKeyedArchiver

存储用法之NSKeyedArchiver

作者: bd8915df25f2 | 来源:发表于2016-11-22 23:13 被阅读0次

    Person.h

    #import <Foundation/Foundation.h>
    
    @interface LoginModel : NSObject
    
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, assign) int age;
    
    @end
    

    Person.m

    #import "LoginModel.h"
    #import "MJExtension.h"
    
    @implementation LoginModel
    //cording
    MJExtensionCodingImplementation
    
    @end
    

    或者
    Person.m

    #import "Person.h"
    //遵守NSCoding协议
    @implementation LoginModel<NSCoding>
    #pragma mark 编码,对象属性进行编码
    - (void)encodeWithCoder:(NSCoder *)aCoder
    {
    //前者(_age,_name)是属性,后者是关键字Key(age,name)
        [aCoder encodeInt:_age forKey:age];
        [aCoder encodeObject:_name forKey:name];
    }
    
    #pragma mark 解码,解码归档数据初始化对象
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self = [super init]) {
            _idNum = [aDecoder decodeIntForKey:age];
            _name = [aDecoder decodeObjectForKey:name];
        }
        return self;
    }
    

    ViewController1:
    保存数据

    Person *p=[[Person alloc] init];
    p.name=@"小王";
    p.age=12;
    
    //设置保存路径
    NSString * CLSLoginDataPath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingString:@"CLSLOGINDATA.data"];
    
    //Encoding保存LoginModel
    [NSKeyedArchiver archiveRootObject:loginModel toFile:CLSLoginDataPath];
    

    ViewController2:
    读取数据

    NSString * CLSLoginDataPath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingString:@"CLSLOGINDATA.data"]
    // Decoding
    Person*p = [NSKeyedUnarchiver unarchiveObjectWithFile:CLSLoginDataPath];
    NSString*name=p.name;
    int age=p.age;
    

    相关文章

      网友评论

          本文标题:存储用法之NSKeyedArchiver

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