NSCache
示例代码如下
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong)NSCache* cache;
@end
@implementation ViewController
-(NSCache *)cache
{
if (_cache==nil) {
_cache=[[NSCache alloc]init];
_cache.totalCostLimit=5;
}
return _cache;
}
- (IBAction)addBtn:(id)sender {
for (NSInteger i=0; i<10; i++) {
NSData *data=[NSData dataWithContentsOfFile:@"/Users/spencer/Desktop/QQ20170218-175829.png"];
[self.cache setObject:data forKey:@(i) cost:1];
NSLog(@"存入了图片%zd",i);
}
}
- (IBAction)checkBtn:(id)sender {
NSLog(@"+++++++++++++++++++++++=");
for (NSInteger i=0; i<10; i++) {
NSData *data=[self.cache objectForKey:@(i)];
if (data) {
NSLog(@"取出了数据%zd",i);
}
}
}
- (IBAction)removeAll:(id)sender {
[self.cache removeAllObjects];
}
@end