应用程序进入后台时清空 NSCache

NSCache emptied when app enters background

我目前使用 NSCache 的 Subclass 来存储一些图像(值)及其相应的名称(键),当应用程序位于前台时,它似乎工作正常。但是,当我按下home button/the 用户进入后台,我重新进入应用程序时,NSCache 是空的。

实现细节:我将 NSCache 的子class实现为单例。这确保应该只有一个 class 的实例,只需调用 class 名称和共享实现,就可以从程序中的任何地方访问它。 [HelloCache sharedCache]。这里的HelloCache是​​subclass的名字,sharedCache是​​共享的Cache.

认为您需要确保放置在缓存中的对象符合 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.