NSCache的一些自动删除策略是什么?苹果的文档没有提到它们,我在实验中发现NSCache不会响应内存警告。
发布于 2012-06-02 08:44:37
您最好将NSCache视为一个黑盒,尽可能多地使用它。
来自Caching and Purgeable Memory (重点是我的):
向缓存添加项时,可以指定与每个键值对关联的成本值。调用
setTotalCostLimit:方法来设置所有缓存对象成本总和的最大值。因此,当添加一个将totalCost推到totalCostLimit之上的对象时,缓存可能会自动驱逐它的一些对象,以便回到阈值以下。对于此逐出过程不能保证,因此试图操纵cost值来实现特定行为可能会损害缓存的性能。如果没有任何有用的信息,请传入00cost,或者使用setObject:forKey:方法,该方法不需要传入开销。
注意:数量限制和总成本限制没有严格执行。也就是说,当缓存超过其限制之一时,它的一些对象可能会立即被逐出、稍后被逐出或永远不被逐出,这完全取决于缓存的实现细节。
发布于 2013-05-09 12:23:18
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];
}
@endhttps://stackoverflow.com/questions/10858815
复制相似问题