YYCache是一个缓存框架,由YYCache、YYDiskCache、YYMemoryCache和YYKVStorage组成。在项目开发过程中,想通过YYCache存储一个自定义对象,这个对象包括文章的ID、标题、图片、作者。但是在存储的过程中发现,YYCache并不能将此对象成功存储到本地,查看API后发现,如果保存的自定义对象不遵守NSCoding的协议或不实现NSCoding协议的方法,就不能使用YYDiskCache进行长期缓存。
也就是说通过YYCache存储自定义对象的时候,需要对该自定义对象先进行归档与反归档的操作,这样才能将其成功存储到本地。
通过YYCache实现存储自定义对象的步骤:
一、创建自定义对象ArticleCacheModel,包括属性文章的ID、标题、图片、作者,同时遵循<NSCoding>协议
@interface ArticleCacheModel: NSObject <NSCoding>
+ (instancetype)shareInstace;
@property(nonatomic, copy)NSString *articleTitle;
@property(nonatomic, copy)NSString *imageUrl;
@property(nonatomic, copy)NSString *authorName;
@property(nonatomic, assign)NSInteger articleID;
@end
二、对自定义对象做归档与反归档的操作
归档(序列化)
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInteger:self.articleID forKey:@"articleID"];
[aCoder encodeObject:self.authorName forKey:@"authorName"];
[aCoder encodeObject:self.articleTitle forKey:@"articleTitle"];
[aCoder encodeObject:self.imageUrl forKey:@"imageUrl"];
}
反归档(反序列化)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self.articleID = [aDecoder decodeIntForKey:@"articleID"];
self.authorName = [aDecoder decodeObjectForKey:@"authorName"];
self.articleTitle = [aDecoder decodeObjectForKey:@"articleTitle"];
self.imageUrl = [aDecoder decodeObjectForKey:@"imageUrl"];
return self;
}
三、将自定义的对象用YYCache储存到本地
YYCache *_dataCache =[[YYCache alloc] initWithName:@"ArticleCache"];
_dataCache.memoryCache.shouldRemoveAllObjectsOnMemoryWarning=YES;
ArticleCacheModel *cacheModel = [ArticleCacheModel shareInstace];
cacheModel.articleID = @”文章ID”;
cacheModel.articleTitle = @”文章标题”;
cacheModel.imageUrl = @”图片地址”;
cacheModel.authorName = @”作者名字”;
//存储到本地
[_dataCache setObject: cacheModel forKey:@“cacheModelKey”];
通过key取本地值
ArticleCacheModel *cacheModel = [YYCache objectForKey: @“cacheModelKey”];
NSLog(@”%@”,cacheModel);
网友评论