NSCache使用

//
//  ViewController.swift
//  缓存类使用
//
//  Created by admin on 16/2/24.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController,NSCacheDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    lazy var cache:NSCache = {
        let tempCache = NSCache()
        // NSUInteger totalCostLimit;  "成本" 限制, 默认是 0 (没有限制)
        // 图片 像素 == 总的像素点
//        tempCache.totalCostLimit = 10
        // countLimit;  数量的限制  默认是 0(无限制) 
        // 设置数量的限制。 一旦超出限额,会自动删除之前添加的内容
        tempCache.countLimit = 10
        tempCache.delegate = self
        return tempCache
    }()
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }
    @IBAction func readCaches(button:UIButton)
    {

        for var i = 0;i < 20;i++
        {
            // 读缓存,不存在则为nil
            print(cache.objectForKey("\(i)"))
        }
    }
    @IBAction func writeCaches(button:UIButton)
    {
        for var i = 0;i < 20;i++
        {
            // 加缓存
            cache.setObject(i, forKey: "\(i)")
        }
    }
    // NSCache代理,清除缓存时会通知
    func cache(cache: NSCache, willEvictObject obj: AnyObject) {
        print("清空缓存\(obj)")
    }
}

标签: swift

添加新评论