Search code examples
swiftcachingswiftui

Objects do not added to cache by clicking on button


I am trying to use simple object caching. In this example, I am assuming that the first time the button is clicked, the object will be added to the cache, and then it will be fetched from the cache. But every time I click on the button, I get a message that the object has been added to the cache again, although it should already be taken from the cache.

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: {
            let cache = NSCache<NSString, TestObject>()
            let myObject: TestObject
            if let cachedVersion = cache.object(forKey: "cachedObject") {
                print("Get cache")
                myObject = cachedVersion
            } else {
                print("Set cache")
                myObject = TestObject()
                cache.setObject(myObject, forKey: "cachedObject")
            }
        }, label: {
            Text("Cache it!")
        })
    }
}

class TestObject: Codable {
    var status: String = ""
    var totalResults: Int = 0
    var posts: String = "PostsObject"
}

And I always get Set cache message in console.

Where is the mistake?


Solution

  • try putting

    let cache = NSCache<NSString, TestObject>()
    

    outside the

    var body: some View
    

    As you have it, a new cache is created every time you press the button.