Reputation: 1531
This might be the expected behavior, but is not clearly stated by Apple.
I am using NSCache
to cache some images for my UICollectionView
. When I put the app in the background and open it again (immediately), all of my images are no longer in the NSCache
.
Ideally, I would like the most recently loaded images to stay cached so that when the user re-opens the app they don't have to pay the cost of loading all of the images again. It seems like NSCache
should allow a less aggressive caching policy.
I just wanted to post here for a sanity check and make sure I'm not missing anything obvious.
Otherwise, I'm going to have to implement my own cache that just keeps the last 25 loaded images in an NSMutableDictionary
cache.
Upvotes: 9
Views: 4678
Reputation: 236
I was also having same issue, “cached images in NSCache evicted when app goes into background”. I did create an example to handle this issue, available in github https://github.com/SurendraK11/CachingImage/tree/master/CachingImages
Import thing is to not here, UIImage is not cached into NSCache directly. This is wrapped into CacheItem generic class which confirm NSDiscardableContent where isContentDiscarded return false and beginContentAccess return true
More information about NSDiscardableContent https://developer.apple.com/documentation/foundation/nsdiscardablecontent
Upvotes: 0
Reputation: 289
It looks like you need to implement NSDiscardableContent protocol for the objects you put in NSCache. When objects in the cache don't conform to NSDiscardableContent, they're evicted on backgrounding the app according to this answer. https://stackoverflow.com/a/13579963
Upvotes: 5
Reputation: 38162
The apple docs says:
The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint.
So it removes some items, not all items. It depends on NSCache internal policies, available memory, device status, etc. Also, read a bit on NSDiscardableContent protocol as well.
From the docs:
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.
Upvotes: 3