NSCache 基本使用
NSCache缓存类介绍
NSCache源码
/* NSCache.h
Copyright (c) 2008-2018, Apple Inc. All rights reserved.
*/
#import <Foundation/NSObject.h>
@class NSString;
@protocol NSCacheDelegate;
NS_ASSUME_NONNULL_BEGIN
NS_CLASS_AVAILABLE(10_6, 4_0)
@interface NSCache <KeyType, ObjectType> : NSObject {
@private
id _delegate;
void *_private[5];
void *_reserved;
}
@property (copy) NSString *name;
@property (nullable, assign) id<NSCacheDelegate> delegate;
- (nullable ObjectType)objectForKey:(KeyType)key;
- (void)setObject:(ObjectType)obj forKey:(KeyType)key; // 0 cost
/**
//在缓存中设置指定键名对应的值,并且指定该键值对的成本,用于计算记录在缓存中的所有对象的总成本,出现内存警告或者超出缓存总成本上限的时候,缓存会开启一个回收过程,删除部分元素
*/
- (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g;
- (void)removeObjectForKey:(KeyType)key;
- (void)removeAllObjects;
//设置最大的缓存成本(量) (单个成本*总个数) 这个成本是一个单位概念
//SD框架中图片的成本计算方式是这样的 image.size.height * image.size.width * image.scale * image.scale SD框架中图片的成本计算
@property NSUInteger totalCostLimit; // limits are imprecise/not strict
//设置最大缓存数据的数量,如果超出该限制那么内部会自动开启一个回收过程把最先存储的数据删除
@property NSUInteger countLimit; // limits are imprecise/not strict
@property BOOL evictsObjectsWithDiscardedContent;
@end
@protocol NSCacheDelegate <NSObject>
@optional
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
@end
NS_ASSUME_NONNULL_END