写在前面:我们知道,在使用第三方SDWebImage框架时,其内部已经帮我们做好了缓存,我们只需要选择一种缓存策略即可(大多数情况下我们选择默认0)。观察其代码,作者用来做缓存使用的就是NSCache这个类,相比较我们使用字典数组来做缓存而言,这个类本身就存在很多优点,比如:线程安全、当内存很低时,自动清理缓存以及非常方便的控制缓存数。
下面,我直接贴上代码,你们一看就懂。
注意:
//这个方法和属性配合使用
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
@property NSUInteger totalCostLimit; // limits are imprecise/not strict
.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
.m文件
#import "ViewController.h"
@interface ViewController ()<NSCacheDelegate>
/** 注释 */
@property (nonatomic, strong) NSCache *cache;
@end
@implementation ViewController
-(NSCache *)cache
{
if (_cache == nil) {
_cache = [[NSCache alloc]init];
_cache.totalCostLimit = 5;//总成本数是5 ,如果发现存的数据超过中成本那么会自动回收之前的对象
_cache.delegate = self;
}
return _cache;
}
//存数据
- (IBAction)addBtnClick:(id)sender
{
//NSCache的Key只是对对象进行Strong引用,不是拷贝(和可变字典的区别)
for (NSInteger i = 0; i<10; i++) {
NSData *data = [NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/Snip20160221_38.png"];
//cost:成本
[self.cache setObject:data forKey:@(i) cost:1];
NSLog(@"存数据%zd",i);
}
}
//取数据
- (IBAction)checkBtnClick:(id)sender
{
NSLog(@"+++++++++++++++");
for (NSInteger i = 0; i<10; i++) {
NSData *data = [self.cache objectForKey:@(i)];
if (data) {
NSLog(@"取出数据%zd",i);
}
}
}
//删除数据
- (IBAction)removeBtnClick:(id)sender
{
[self.cache removeAllObjects];
}
#pragma mark ----------------------
#pragma mark NSCacheDelegate
//即将回收对象的时候调用该方法
-(void)cache:(NSCache *)cache willEvictObject:(id)obj
{
NSLog(@"回收%zd",[obj length]);
}
@end