🚩 | 问题
什么是序列化和反序列化,可以用来做什么?如何在OC中实现复杂对象的存储?
📌 | 解答
序列化就是讲对象转换成字节的序列的过程;反序列化就是讲字节还原成对象的过程
可以用来做将对象保存沙盒中或者数据库中,并且能够读取出来
需要遵守NSCoding协议
#import <Foundation/Foundation.h>
@interface JXAccount : NSObject<NSCoding>
/** 户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID字段来做登录识别。 */
@property (nonatomic,strong) NSString * access_token;
/** access_token的生命周期,单位是秒数 */
@property (nonatomic,strong) NSString * expires_in;
/** 授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户登录状态的识别,只有access_token才是用户授权的唯一票据 */
@property (nonatomic,strong) NSString * uid;
/** 过期时间 */
@property (nonatomic,strong) NSDate * expires_time;
/** 用户昵称 */
@property (nonatomic,copy) NSString * name;
/**
* 将模型转换成字典
*/
+(instancetype)accountWithDict:(NSDictionary *)dict;
@end
#import "JXAccount.h"
@implementation JXAccount
+ (instancetype)accountWithDict:(NSDictionary *)dict {
JXAccount * account = [[self alloc] init];
account.access_token = dict[@"access_token"];
account.expires_in = dict[@"expires_in"];
account.uid = dict[@"uid"];
// 确定账号过期时间:账号创建的时间加上有效期
NSDate * now = [NSDate date];
account.expires_time = [now dateByAddingTimeInterval:account.expires_in.doubleValue];
return account;
}
/**
* 当从文件中读取一个对象的时候调用
* 在这个方法中写清楚怎么解析文件中的数据,利用key来解析数据
*/
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
self.expires_in = [aDecoder decodeObjectForKey:@"expires_in"];
self.uid = [aDecoder decodeObjectForKey:@"uid"];
self.expires_time = [aDecoder decodeObjectForKey:@"expires_time"];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
/**
* 当将一个对象存储到文件中的时候需要调用
* 这这个方法中写清楚要存储哪些属性,以及定义怎么存储属性,以及存储哪些属性
*/
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.access_token forKey:@"access_token"];
[aCoder encodeObject:self.expires_in forKey:@"expires_in"];
[aCoder encodeObject:self.uid forKey:@"uid"];
[aCoder encodeObject:self.expires_time forKey:@"expires_time"];
[aCoder encodeObject:self.name forKey:@"name"];
}
@end