NSCache是苹果官方提供的缓存类,用法与NSMutableDictionary的用法很相似,在AFNetworking和SDWebImage中,使用它来管理缓存
#import "ViewController.h"
@interface ViewController()<NSCacheDelegate>
@property (nonatomic, strong) NSCache *myCache;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
for (int i =0 ; i< 5; i++) {
// 向缓存中添加对象
NSString *str = [NSString stringWithFormat:@"cache - %d", I];
[self.myCache setObject:str forKey:@(i)];
}
for (int i=0 ; i< 5; i++) {
NSLog(@"%@", [self.myCache objectForKey:@(i)]);
}
}
-(NSCache *)myCache
{
if (_myCache == nil) {
_myCache = [[NSCache alloc] init];
_myCache.countLimit = 3;
_myCache.delegate = self;
}
return _myCache;
}
#pragma mark- delegate
-(void)cache:(NSCache *)cache willEvictObject:(id)obj
{
NSLog(@"要删除的对象obj-------------%@", obj);
}
@end
cache.png