编写高质量代码的52个有效方法

52个有效方法(50) - 构建缓存时,选用NSCache而非N

2018-10-09  本文已影响15人  SkyMing一C
NSCache

NSCache是苹果官方提供的缓存类,用法与NSMutableDictionary的用法很相似,在AFNetworkingSDWebImage中,使用它来管理缓存。

NSCache的属性
NSCache的方法
委托方法
#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
NSPurgeableData
#import "ViewController.h"

@interface ViewController ()
{
    NSCache *_cache;
}
@end

@implementation ViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _cache = [[NSCache alloc] init];
        _cache.countLimit = 100;
        _cache.totalCostLimit = 5 * 1024 * 1024;
    }
    return self;
}

- (void)downloadWithURL:(NSURL *)url
{
    NSPurgeableData *cacheData = [_cache objectForKey:url];
    if (cacheData) {
        [cacheData beginContentAccess];
        
        [self useData:cacheData];
        
        [cacheData endContentAccess];
    }else{
        //network init
        //network block -->data
        {
            NSPurgeableData *purgeableData = [[NSPurgeableData alloc] initWithData:data];
            [_cache setObject:purgeableData forKey:url cost:purgeableData.length];
            
            [self useData:cacheData];
            
            [purgeableData endContentAccess];
        }
    }
}

- (void)useData:(NSPurgeableData *)data {}

@end
要点
  1. 实现缓存时应选用NSCache而非NSDictionary对象。因为NSCache可以提供优雅的自动删减功能,而且是“线程安全的”,此外,它与字典不同,并不会拷贝键。

  2. 可以给NSCache对象设置上限,用以限制缓存中的对象总个数及“总成本”,而这些尺度则定义了缓存删减其中对象的时机。但是绝对不要把这些尺度当成可靠的“硬限制”,他们仅对NSCache起知道作业。

  3. 将NSPurgeableData与NSCache搭配使用,可实现自动清除数据的功能,也就是说,当NSPurgeableData对象所占内存为系统所丢弃时,该对象自身也会从缓存中移除。

  4. 如果缓存使用得当,那么应用程序的响应速度就能提高。只有那种“重新计算起来很费事的”数据,才值得放入缓存,比如那些需要从网络获取或从磁盘读取的数据。

上一篇 下一篇

猜你喜欢

热点阅读