Evi*_*oer 8 iphone cocoa-touch objective-c ios
什么是NSCache的自动删除策略?Apple的文档没有提及它们,我通过实验发现NSCache没有响应内存警告.
NSCache没有响应UIApplicationDidReceiveMemoryWarningNotification,但它会在低内存情况下自动驱逐其对象,显然使用其他一些机制.
虽然我之前建议观察UIApplicationDidReceiveMemoryWarningNotification,但事实并非如此.不需要对低内存情况进行特殊处理,因为NSCache它会自动处理.
更新:
从iOS 7开始,它NSCache不仅不响应内存警告,而且在内存压力下也似乎没有正确清除自身(请参阅NSCache在达到内存限制时崩溃(仅限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
Run Code Online (Sandbox Code Playgroud)
你最好NSCache尽可能多地作为黑匣子来对待.
从缓存和可清除内存(强调我的):
将项目添加到缓存时,您可以指定与每个键值对关联的成本值.调用
setTotalCostLimit:方法设置所有缓存对象成本总和的最大值.因此,当添加推送totalCost上述对象的对象时totalCostLimit,高速缓存可以自动驱逐其一些对象以便回到阈值以下.此驱逐过程无法保证,因此尝试操纵cost值以实现特定行为可能会对缓存的性能产生不利影响.传入0的cost,如果你有没有什么用处,或者使用setObject:forKey:方法,它不需要传递成本.注意:未严格执行计数限制和总成本限制.也就是说,当缓存超过其中一个限制时,其某些对象可能会立即,稍后或永远被驱逐,这取决于缓存的实现细节.