前言:首先缓存分为内存缓存跟硬盘缓存两种,而内存缓存的实现一般使用LRU算法来实现,硬盘缓存要么基于文件要么基于数据,要么结合文件缓存以及数据库缓存两种来实现。YYCache的内存缓存实现是基于双向链表来实现LRU算法,他的硬盘缓存是基于结合文件缓存以及数据库两者来实现的。
1.YYCache的使用场景:存服务器传过来的数据,以减少服务器的压力,避免每次都向服务器请求。 缓存的方式分为两种分别为内存缓存和磁盘缓存,内存缓存速度快容量小,磁盘缓存容量大速度慢可持久化存储。
2.YYCache相对与其他三方缓存策略的对比,参考官方的说明文档
3.YYCache的使用:
#import <Foundation/Foundation.h>
@interface Pet : NSObject<NSCoding>
@property (nonatomic, copy) NSArray *petName;
@property (nonatomic, copy) NSString *petSex;
@end
#import "Pet.h"
@implementation Pet
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.petName forKey:@"petName"];
[aCoder encodeObject:self.petSex forKey:@"petSex"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
self.petName = [aDecoder decodeObjectForKey:@"petName"];
self.petSex = [aDecoder decodeObjectForKey:@"petSex"];
return self;
}
#import <Foundation/Foundation.h>
#import "Pet.h"
@interface Person : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, copy) NSString *age;
@property (nonatomic, strong) Pet *pet;
@end
#import "Person.h"
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.age forKey:@"age"];
[aCoder encodeObject:self.sex forKey:@"sex"];
[aCoder encodeObject:self.pet forKey:@"pet"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeObjectForKey:@"age"];
self.sex = [aDecoder decodeObjectForKey:@"sex"];
self.pet = [aDecoder decodeObjectForKey:@"pet"];
return self;
}
@end
开始使用YYCache缓存
#import "ViewController.h"
#import "YYCache.h"
#import "Person.h"
#import "Pet.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
YYCache *personCache = [YYCache cacheWithName:@"personCache"];
Person *person = [[Person alloc] init];
person.name = @"hxg";
person.age = @"11";
person.sex = @"女";
Pet *pet = [[Pet alloc] init];
pet.petName = @[@"111",@"222",@"33"];
pet.petSex = @"男";
person.pet = pet;
[personCache setObject:person
forKey:@"personInfo"];
NSLog(@"%@",[[(Person *)[personCache objectForKey:@"personInfo"] pet] petName]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSLog(@"%@",docDir);
}
然后到打印的目录下去看生成的缓存文件如下: