美文网首页
本地存储方式-归档

本地存储方式-归档

作者: nickNameDC | 来源:发表于2016-05-03 15:47 被阅读0次
    归档用于存储模型
    #define DCAccountFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"account.data"]
    
    'DCAccountFilePath为存储地址'
    
    1.'存储
    + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
    //示例
     [NSKeyedArchiver archiveRootObject:account toFile:DCAccountFilePath];
    2.'解析
    + (nullable id)unarchiveObjectWithFile:(NSString *)path;
    //示例
    DCAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:DCAccountFilePath];
    
    3.'要存储的模型必须遵守NSCoding协议,并完成协议中的方法
    @interface DCEmotion : NSObject<NSCoding>
    
    - (void)encodeWithCoder:(NSCoder *)aCoder;
    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;
    
    //存储
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [aCoder encodeObject:self.access_token forKey:@"access_token"];
        [aCoder encodeObject:self.expires_in forKey:@"expires_in"];
        [aCoder encodeObject:self.expires_end forKey:@"expires_end"];
        [aCoder encodeObject:self.uid forKey:@"uid"];
    }
    //读取
    -(instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super init];
        if(self)
        {
            self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
            self.expires_in = [aDecoder decodeObjectForKey:@"expires_in"];
            self.expires_end = [aDecoder decodeObjectForKey:@"expires_end"];
            self.uid = [aDecoder decodeObjectForKey:@"uid"];
        }
        return self;
    }
    
    

    相关文章

      网友评论

          本文标题:本地存储方式-归档

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