当应用程序进入后台时,NSCache清空 [英] NSCache emptied when app enters background

查看:422
本文介绍了当应用程序进入后台时,NSCache清空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用NSCache的子类来存储一些具有相应名称(键)的图像(值),并且当应用程序处于前台时,它似乎可以正常工作.但是,当我按下主页按钮/用户进入背景并重新输入该应用程序时,NSCache为空.

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.

实现细节:我将NSCache的子类实现为Singleton.这样可以确保只存在该类的一个实例,只需调用类名和共享实现即可从程序的任何位置进行访问. [HelloCache sharedCache].这里的HelloCache是​​子类的名称,sharedCache是​​共享的Cache.

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.

推荐答案

认为您需要确保放置在缓存中的对象符合 NSCache类参考:

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

存储在NSCache对象中的常见数据类型是 实现NSDiscardableContent协议.存储这种类型的 缓存中的对象有好处,因为它的内容可以被丢弃 当不再需要它时,可以节省内存.默认情况下, 缓存中的NSDiscardableContent对象会自动删除 从缓存中删除其内容(尽管此自动 删除政策可以更改.如果NSDiscardableContent对象是 放入缓存后,缓存会在其上调用throwsContentIfPossible 移除后.

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.

这篇关于当应用程序进入后台时,NSCache清空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆