0

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Devxln
  • 556
  • 6
  • 18

1 Answers1

0

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.

johnny
  • 1,434
  • 1
  • 15
  • 26
  • removeAllObjects() did not clear the cache of old instances when a new instance has been created. The memory is not the same, that's my point - I need to get access to previous instances of NSCache to delete them. – Devxln Apr 04 '19 at 17:11
  • 1
    Right, I'm saying you shouldn't have multiple cache instances. You need to have references to those NSCache objects in order to get them back. Creating multiple NSCache objects then losing them will cause a memory leak, which is what you're seeing. You should create a CacheManager class (or something like that) and manage it that way. – johnny Apr 04 '19 at 17:20
  • The only instances I create are on initial load of the application; but is there a way to "save" these instances to the disk and then reuse if the application opens again? – Devxln Apr 04 '19 at 17:23