How to delete all cache in NSCache?

2.6k Views Asked by At

I am using NSCache for caching objects. Is there a way to delete all cache at once?

I am using the following methods to cache:

class VC: UIViewController {
    static let userCache = NSCache<NSString, User>()

    func getUser(fromId id: String, completion: @escaping (_ user: User) -> Void) {
        if let cachedVersion = VC.userCache.object(forKey: id as NSString) {
            print("using cached user from id")
            completion(cachedVersion)
            return
        }

        // retrieve new instance of object
    }
}

But I see the Documents & Data section increasing by time (currently 140MB+). I tried to clear cache using the following method, but that didn't work out:

VC.userCache.removeAllObjects()

Is there a way to retrieve an old instance of NSCache so I do not have to create a new instance each time the app is loaded? Or is there a way to delete all cached objects when the app loads?

1

There are 1 best solutions below

3
johnny On

What do you mean removeAllObjects() didn't work? Are you sure the memory you're using is from this cache? If the cache is being used by multiple ViewControllers, you should create and manage it outside of those ViewControllers so that you're not creating multiple instances, e.g. CacheManager class or something of the sort.

There are also countLimit and totalCostLimit properties you can set on your cache so that it doesn't balloon in size.