1

I don't know what I am missing here to cache object. But no object is ever cached in the disk

import UIKit

class MyObject {
    var title:String?
    var desc:String?

    init(title: String, desc: String) {
        self.title = title
        self.desc = desc
    }
}

class ViewController: UIViewController {

    let cache = NSCache<NSString, MyObject>()
    var myObject:MyObject?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let cachedVersion = cache.object(forKey: "CachedObject") {
            // use the cached version
            myObject = cachedVersion
        } else {
            // create it from scratch then store in cache
            let object = MyObject(title: "title", desc: "desc")
            cache.setObject(object, forKey: "CachedObject")
        }
    }
}

After running the Xcode project the 2nd time around, I would expect to see a value for the key "CachedObject"

enter image description here

  • NSCache it is not persistent. If you need to persist (save to disk) you need to make your class NSCoding compliant and use NSKeyedArchiver to convert your custom object to Data or if you are coding in Swift 4 or later you can use Codable protocol. – Leo Dabus May 27 '18 at 18:51
  • Possible duplicate of [Save NSCache Contents to Disk](https://stackoverflow.com/questions/4542707/save-nscache-contents-to-disk) – Anton Belousov May 27 '18 at 19:14

0 Answers0