YYCache是一個(gè)緩存框架郭赐,由YYCache抡诞、YYDiskCache斟叼、YYMemoryCache和YYKVStorage組成踱葛。在項(xiàng)目開發(fā)過程中丹莲,想通過YYCache存儲(chǔ)一個(gè)自定義對(duì)象,這個(gè)對(duì)象包括文章的ID尸诽、標(biāo)題甥材、圖片、作者性含。但是在存儲(chǔ)的過程中發(fā)現(xiàn)洲赵,YYCache并不能將此對(duì)象成功存儲(chǔ)到本地,查看API后發(fā)現(xiàn),如果保存的自定義對(duì)象不遵守NSCoding的協(xié)議或不實(shí)現(xiàn)NSCoding協(xié)議的方法板鬓,就不能使用YYDiskCache進(jìn)行長期緩存悲敷。
也就是說通過YYCache存儲(chǔ)自定義對(duì)象的時(shí)候究恤,需要對(duì)該自定義對(duì)象先進(jìn)行歸檔與反歸檔的操作俭令,這樣才能將其成功存儲(chǔ)到本地。
通過YYCache實(shí)現(xiàn)存儲(chǔ)自定義對(duì)象的步驟:
一部宿、創(chuàng)建自定義對(duì)象ArticleCacheModel,包括屬性文章的ID抄腔、標(biāo)題、圖片理张、作者赫蛇,同時(shí)遵循<NSCoding>協(xié)議
@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
二、對(duì)自定義對(duì)象做歸檔與反歸檔的操作
歸檔(序列化)
- (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;
}
三雾叭、將自定義的對(duì)象用YYCache儲(chǔ)存到本地
YYCache *_dataCache =[[YYCache alloc] initWithName:@"ArticleCache"];
_dataCache.memoryCache.shouldRemoveAllObjectsOnMemoryWarning=YES;
ArticleCacheModel *cacheModel = [ArticleCacheModel shareInstace];
cacheModel.articleID = @”文章ID”;
cacheModel.articleTitle = @”文章標(biāo)題”;
cacheModel.imageUrl = @”圖片地址”;
cacheModel.authorName = @”作者名字”;
//存儲(chǔ)到本地
[_dataCache setObject: cacheModel forKey:@“cacheModelKey”];
通過key取本地值
ArticleCacheModel *cacheModel = [YYCache objectForKey: @“cacheModelKey”];
NSLog(@”%@”,cacheModel);