本地存储方式-归档

2016-05-03  本文已影响0人  nickNameDC
归档用于存储模型
#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;
}

上一篇 下一篇

猜你喜欢

热点阅读