NSCache emptied when app enters background
Asked Answered
A

1

10

I currently use a Subclass of NSCache to store some images (values) with their corresponding names (Keys) and it seems to work fine, when the app is in the foreground. However, when I press the home button/the user enters the background and I reenter the app, the NSCache is empty.

Implementation details: I implemented my subclass of NSCache as a Singleton. This ensures that there should be only one instance of that class, which should be accessible from anywhere in the program by simply calling the class name along with the shared implementation. [HelloCache sharedCache]. Here HelloCache is the name of the subclass and sharedCache is the shared Cache.

Astronomical answered 19/11, 2015 at 18:46 Comment(0)
A
6

Think you need to ensure that objects placed in cache conform to NSDiscardableContentProtocol to have desired results. From the NSCache Class Reference:

A common data type stored in NSCache objects is an object that implements the NSDiscardableContent protocol. Storing this type of object in a cache has benefits, because its content can be discarded when it is not needed anymore, thus saving memory. By default, NSDiscardableContent objects in the cache are automatically removed from the cache if their content is discarded, although this automatic removal policy can be changed. If an NSDiscardableContent object is put into the cache, the cache calls discardContentIfPossible on it upon its removal.

Abcoulomb answered 19/11, 2015 at 19:5 Comment(3)
could you be a bit more specific please, about how that would solve the problem?Astronomical
NSCache is essentially a glorified NSMutableDictionary except it releases objects during times when memory is constrained. However, it needs some instructions on when and what to release. So it looks to the NSDiscardableContent protocol to make those kinds of determinations. When objects don't implement this, it will retain the object while the app is active and release those objects NSCache deems it convenient (which is every time the app enters the background). You can see here:https://mcmap.net/q/778717/-nscache-and-background/… as wellAbcoulomb
@Abcoulomb Your comment here is much more informative than your answer!Methaemoglobin

© 2022 - 2024 — McMap. All rights reserved.