NSCache不会驱逐数据

NSCache不会驱逐数据

本文介绍了NSCache不会驱逐数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是一个很少使用的工具,实际上看起来很有用。我创建了一个简单的实验,看它是如何工作的,看起来它在低内存情况下不会自动驱逐数据(或者我做错了!)

NSCache is a rarely used tool which actually looks quite useful. I created a simple experiment to see how it works and it looks like it does not auto-evict data in low memory situations (or I am doing something wrong!)

- (void)viewDidLoad
{
    _testCache = [[NSCache alloc] init];

    // Allocate 600 MB of zeros and save to NSCache
    NSMutableData* largeData = [[NSMutableData alloc] init];
    [largeData setLength:1024 * 1024 * 600];
    [_testCache setObject:largeData forKey:@"original_Data"];
}

- (IBAction)buttonWasTapped:(id)sender {

    // Allocate & save to cache 300 MB each time the button is pressed
    NSMutableData* largeData = [[NSMutableData alloc] init];
    [largeData setLength:1024 * 1024 * 300];
    static int count = 2;
    NSString* key = [NSString stringWithFormat:@"test_data_%d", count++];
    [_testCache setObject:largeData forKey:key];

    NSMutableData* dataRecoveredFromCache = [_testCache objectForKey:@"original_Data"];

    if (dataRecoveredFromCache) {
        NSLog(@"Original data is ok");
    } else {
        NSLog(@"Original data is missing (purged from cache)");
    }
}

所以我在模拟器中运行应用程序,并录音按钮几次,但没有物品被驱逐......该应用程序最终崩溃:

So I ran the app in the simulator, and taped the button a few times however no items were evicted... The app eventually crashed:

2012-07-17 14:19:36.877 NSCacheTest[15302:f803] Data is ok
2012-07-17 14:19:37.365 NSCacheTest[15302:f803] Data is ok
2012-07-17 14:19:37.861 NSCacheTest[15302:f803] Data is ok
2012-07-17 14:19:38.341 NSCacheTest[15302:f803] Data is ok
2012-07-17 14:19:38.821 NSCacheTest[15302:f803] Data is ok
NSCacheTest(15302,0xac0942c0) malloc: *** mmap(size=393216000) failed (error code=12)
*** error: can't allocate region


推荐答案

从doc(Emphasis mine): NSCache类包含各种自动删除策略,确保它不会占用太多的系统内存。如果其他应用程序需要内存,系统会自动执行这些策略。调用时,这些策略会从缓存中删除一些项目,从而最大限度地减少内存占用。

From the doc (Emphasis mine): The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint.

Apple没有声明内存将在内存警告中释放 - 根据我的经验,当应用程序转到后台或添加更多大元素时,缓存最常被清除。

Apple does not state that the memory will be freed on memory warning - in my experience, the cache is most often purged when the app goes to background or when you add more large elements.

这篇关于NSCache不会驱逐数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:52