@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;
// 总成本限制
@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
import CoreFoundation
import CoreGraphics
import Darwin
import Darwin.uuid
import Foundation
/* NSCache.h
Copyright (c) 2008-2016, Apple Inc. All rights reserved.
*/
@available(iOS 4.0, *)
open class NSCache<KeyType, ObjectType> : NSObject where KeyType : AnyObject, ObjectType : AnyObject {
// 缓存的名称
open var name: String
// 缓存代理
unowned(unsafe) open var delegate: NSCacheDelegate?
// 获取对象
open func object(forKey key: KeyType) -> ObjectType?
// 添加对象
open func setObject(_ obj: ObjectType, forKey key: KeyType) // 0 cost
// 根据成本添加对象
open func setObject(_ obj: ObjectType, forKey key: KeyType, cost g: Int)
// 移除对象
open func removeObject(forKey key: KeyType)
// 移除所有对象
open func removeAllObjects()
// 总成本限制
open var totalCostLimit: Int // limits are imprecise/not strict
// 个数限制
open var countLimit: Int // limits are imprecise/not strict
// 是否管理可废弃内容
open var evictsObjectsWithDiscardedContent: Bool
}
public protocol NSCacheDelegate : NSObjectProtocol {
@available(iOS 4.0, *)
optional public func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any)
}
NSCache
NSCache 对象是一个可变的集合,用来存储键值对,类似于 NSDictionary。NSCache 类提供了添加和删除对象的接口,根据总的成本和缓存的对象的个数设置回收策略。
概览
NSCache对象不同于其他可变集合在几个方面:
符号
Managing the Name(管理缓存名字):
- var name: String : 缓存的名称, 默认是空字符串。
Managing Cache Size (管理缓存大小):
var countLimit: Int:缓存持有的最大对象个数, 如果是 0 表示不限制,默认是 0。 这不是一个严格的限制,一旦缓存中的对象超过限制,缓存中的对象可以立即剔除,,具体根据缓存的实现细节。
var totalCostLimit: Int:在剔除缓存对象之前缓存持有的最大总成本,如果是 0 表示不限制,默认是 0。
Managing Discardable Content(管理可废弃的内容):
Managing the Delegate(管理代理):
Getting a Cached Value(获取缓存的值):
- funcobject(forKey: KeyType): 返回和 key 关联的值
Adding and Removing Cached Values(添加也移除缓存值):
func setObject(ObjectType,forKey: KeyType):设置指定 key 的缓存对象。和 NSMutableDictonary 不同,不会复制 key 对象并添加。
func removeObject(forKey: KeyType):移除 key 关联值。
func removeAllObjects(): 置空缓存。