gpt4 book ai didi

iphone - NSCache 自动删除策略

转载 作者:可可西里 更新时间:2023-11-01 03:27:02 25 4
gpt4 key购买 nike

NSCache 的一些自动删除策略是什么? Apple的文档没有提到它们,我实验发现NSCache没有响应内存警告。

最佳答案

NSCache 不响应 UIApplicationDidReceiveMemoryWarningNotification,但它会在内存不足的情况下自动驱逐其对象,显然使用了一些其他机制。

虽然我之前建议观察 UIApplicationDidReceiveMemoryWarningNotification,但事实并非如此。不需要对低内存情况进行特殊处理,因为 NSCache 会自动处理。


更新:

从 iOS 7 开始,NSCache 不仅不响应内存警告,而且似乎也没有在内存压力下正确清除自身(参见 NSCache crashing when memory limit is reached (only on iOS 7))。

我将 NSCache 子类化以观察 UIApplicationDidReceiveMemoryWarningNotification,并在出现内存警告时清除缓存:

@interface AutoPurgeCache : NSCache
@end

@implementation AutoPurgeCache

- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
return self;
}

- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];

// if not ARC, also
//
// [super dealloc];
}

@end

关于iphone - NSCache 自动删除策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10858815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com