问题
When user switches between view controllers via menu, I want to cache them if he has enough memory. In order to do so, I want to use NSCache
to store many UIViewControllers
.
However, I'm not sure how I can tell NSCache
that current object is currently used and should not be removed.
E.g, when I run app, load few view controllers and quit the app, NSCache
automatically delete all viewControllers
(which makes sense - app will be able to stay longer in the foreground). However, it also removes currently displayed view controller which is not what I wanted.
How can I mark particular object as not-removable?
回答1:
You can do like this :
The cache will be removed when the application goes to background. So when the application goes background store the data from cache to {NSUserDefaults} and when application didBecomeActive reassign the value to cache.
回答2:
Cache is an associative memory: you can't strongly decide when to remove a cached item. Instead you can change the cache policy.
From the documentation:
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.
来源:https://stackoverflow.com/questions/14262172/nscache-marking-object-not-removable