NSCache 一个存储键-值对的容器,和NSDictionary 很像,它可以设置存储键-值对的最大数量
1.NSCache 包含了回收策略,确保了NSCache 不会使用太多系统的内存,如果其它应用需要内存,它会自动移除一些键-值对来释放一定的内存供其它应用使用,最大限度地减少其内存占用。 2.它是线程安全对象,你可以在其他线程增加,删除和查询Cahe 不需要加锁 3.不像NSMutableDictionary 对象,cache不会复值添加到它里面的对象
open var name: String
var countLimit: Int { get set }
提示:
限制不是严格的限制,如果缓存超过限制,缓存中的对象可能会被立刻移除,或者永远不会被移除,取决于缓存的实现机制(我也不太理解为什么这么搞)
var totalCostLimit: Int { get set }
提示:
这个值代表的对象的消耗,如对象的字节大小
var evictsObjectsWithDiscardedContent: Bool { get set }
unowned(unsafe) var delegate: NSCacheDelegate? { get set }
func object(forKey key: KeyType) -> ObjectType?
setObject(ObjectType, forKey: KeyType)
removeObject(forKey: KeyType)
func removeAllObjects()
func setObject(_ obj: ObjectType, forKey key: KeyType, cost g: Int)
let cache = NSCache<AnyObject,AnyObject>()
cache.countLimit = 5
for i in 0...10{
cache.setObject(i as AnyObject, forKey: i as AnyObject)
}
for i in 0...10 {
print(cache.object(forKey: i as AnyObject))
}
运行结果:
nil nil nil nil nil nil Optional(6) Optional(7) Optional(8) Optional(9) Optional(10)
let cache = NSCache<AnyObject,AnyObject>()
cache.totalCostLimit = 10// 设置缓存最大消耗
cache.countLimit = 10
for i in 0...2{
cache.setObject(i as AnyObject, forKey: i as AnyObject,cost:10)// 设置对象最大的消耗
}
for i in 0...2 {
print(cache.object(forKey: i as AnyObject))
}
运行:
nil nil Optional(2)
第一步 首先让你的对象遵守协议NSDiscardableContent
class Dog:NSDiscardableContent{
var isDiscard = false
public func beginContentAccess() -> Bool{
return true
}
public func endContentAccess(){
}
public func discardContentIfPossible(){
}
public func isContentDiscarded() -> Bool{
print("执行了isContentDiscarded")
return isDiscard
}
}
第二步 使用NSCache 把对象缓存起来,evictsObjectsWithDiscardedContent 这个属性必须设置为true
let cache = NSCache<AnyObject,AnyObject>()
cache.evictsObjectsWithDiscardedContent = true
for i in 0...4 {
cache.setObject(Dog(), forKey: i as AnyObject)
}
for i in 0...4 {
print(cache.object(forKey: i as AnyObject))
}
运行结果:
执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded 第三步 将缓存的对象丢弃掉
let x = cache.object(forKey: 0 as AnyObject) as! Dog
x.isDiscard = true
运行一下:
执行了isContentDiscarded 提示: 当我们调用一次或者多次属性和方法时,isContentDiscarded() 会被执行一次
我们再把缓存的对象输出一下看一下
for i in 0...4 {
print(cache.object(forKey: i as AnyObject))
}
运行:
nil 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog) 执行了isContentDiscarded Optional(swift3_0.Dog)
我们发现第一个元素被丢弃了。
optional public func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any)
提示:
设置代理之后,一旦NSCache 缓存的对象被丢弃,会触发这个时间