NSCache是一个很少使用但实际上非常有用的工具。我创建了一个简单的实验来测试它的工作原理,看起来它在低内存情况下不会自动清除数据(或者我做错了什么!)
- (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)");
}
}
我在模拟器中运行了该应用程序,并点击了几次按钮,但没有任何项目被删除... 应用程序最终崩溃:
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
UIApplicationDidReceiveMemoryWarningNotification
的观察者,在其中清空缓存。 - Rob