ios - 当我测试它时,NSCache 在内存压力下不会删除项目,但是文档说它确实如此

标签 ios swift caching

这是我在文档中看到的。

The NSCache class incorporates various auto-eviction policies, which ensure that a cache doesn’t use too much of the system’s memory. If memory is needed by other applications, these policies remove some items from the cache, minimizing its memory footprint.

但是当我查看源代码时:https://github.com/apple/swift-corelibs-foundation/blob/main/Sources/Foundation/NSCache.swift

我看不到它在内存压力下以某种方式删除项目。 它只会在您达到成本限制时删除项目。

我做了一个小测试:

class Data {
    var data = [Int]()

    init() {
        for i in 0..<1000000 {
            data.append(i)
        }
    }
}

var cache = NSCache<NSNumber, Data>()

for i in 0..<10000000 {
    cache.setObject(Data(), forKey: NSNumber(value: i))
}

在该测试之后,应用程序占用了所有内存并崩溃了。 所以。文件是否撒谎?

最佳答案

首先,也是最重要的,swift-corelibs-foundation 不是来自 iOS 和 macOS 的 Foundation:

This project, swift-corelibs-foundation, provides an implementation of the Foundation API for platforms where there is no Objective-C runtime. On macOS, iOS, and other Apple platforms, apps should use the Foundation that comes with the operating system. Our goal is for the API in this project to match the OS-provided Foundation and abstract away the exact underlying platform as much as possible.

接下来,你的测试用例没有仔细测试NSCache。您的 Data 对象可以存储在自动释放池中而不被释放。在这种情况下,情况并非如此,但这是您在测试内存使用情况时需要非常小心的事情。

也就是说,我无法重现您的问题。当我将其放入 iOS 应用程序并在 iOS 12 上运行时,我看到了您可能期望的那种行为:

enter image description here

内存使用量大幅上升至 ~1GB,此时缓存按预期转储。

我也无法在 macOS 上轻松重现它(但我没有足够的耐心让它崩溃,所以它最终可能会崩溃)。您需要提供更准确的示例来说明意外崩溃的位置,以便诊断原因。

关于ios - 当我测试它时,NSCache 在内存压力下不会删除项目,但是文档说它确实如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689444/

相关文章:

java - 使用哪个 Ehcache 导入?

ios - 构造多级dispatchQueue会不会有什么不好的事情发生

ios - Swift 4 中无法使用 'Self' 类型的索引为 'Int' 类型的值添加下标吗?

ios - 如何区分抓拍图像相册中选择的图像

android - 用于制作移动应用程序界面草图的工具

iOS swift 'Could not find member executeFetchRequest'

swift - 如何通过循环组合 TextView ?

caching - 如何在 CakePHP 中的模型函数内使用助手

objective-c - Objective-c 中的基本消息计数

ios - 键盘扩展适用于模拟器,但不适用于设备