1 Similarities and differences between NSCache and NSMutableDictionary
Similarities:
The NSCache and NSMutableDictionary functions are basically the same.
The difference between:
NSCache is thread safe, NSMutableDictionary threads are not thread safe NSCache threads are thread safe, NSCache automatically frees memory when it is low (so always check for empty data when fetching data from the cache). NSCache can specify a cache limit and automatically frees memory when the cache exceeds its limit
Cache quota:
Number of caches @property NSUInteger countLimit;
@property NSUInteger totalCostLimit;
Apple has packaged NSCache with more methods and properties than NSMutableDictionary does
#import "ViewController.h" @interface ViewController () <NSCacheDelegate> @property (nonatomic, strong) NSCache *cache; @end @implementation ViewController - (NSCache *)cache { if (_cache == nil) { _cache = [[NSCache alloc] init]; _cache.countlimit = 5; _cache.totalCostLimit = 1024 * 5; // Set NSCache's delegate _cache.delegate = self; } return _cache; } - (void)viewDidLoad { [super viewDidLoad]; For (int I = 0; i < 10; i++) { [self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"h%d",i]]; NSLog(@" add %@",[NSString stringWithFormat:@"hello %d", I]); } for (int I = 0; i < 10; i++) { NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]); }} - (void)cache:(NSCache *)cache willEvictObject:(id)obj {NSLog(@" remove %@ from cache ",obj); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; [self.cache removeAllObjects] [self.cache removeAllObjects] [self.cache removeAllObjects]; For (int I = 0; i < 10; i++) { NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]); } } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self.cache removeAllObjects]; For (int I = 0; i < 10; i++) { [self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"h%d",i]]; NSLog(@" add %@",[NSString stringWithFormat:@"hello %d", I]); } for (int I = 0; i < 10; i++) { NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]); } } @endCopy the code