NSCache

  • NSCache is a system that provides a cache similar to a collection (NSMutableDictionary). It differs from a collection as follows:

      1. NSCache has the function of automatic deletion to reduce the memory occupied by the system;
      1. NSCache is thread safe and does not require a thread lock.
      1. Key objects are not copied as in NSMutableDictionary. (Keys do not need to implement the NSCopying protocol).
  • NSCache attributes and methods:

    • @property NSUInteger totalCostLimit;

      • When the total amount of memory used by the cache exceeds the value set by totalCostLimit, the system will clear part of the cache until the total amount of memory used by the cache falls below the value set by totalCostLimit.
    • @property NSUInteger countLimit;

      • Set the size of the cache object, which is not a strict limit.
    • (id)objectForKey:(id)key;

      • Gets the cache object, based on the key-value pair
    • (void)setObject:(id)obj forKey:(id)key; // 0 cost

      • Store cache objects, taking into account the cache’s limiting properties;
    • (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g;

      • – (void)setObject (id)obj forKey (id)key; – (void)setObject (id)obj forKey;
  • NSCacheDelegate agent

The proxy properties are declared as follows:

  • @property (assign) iddelegate;

    • When the cache object is about to be cleaned up, the system calls back the NSCacheDelegate proxy as follows:
    • (void)cache:(NSCache *)cache willEvictObject:(id)obj;

      • The first argument is the current cache (NSCache). Do not modify this object;

      • The second argument is the object that is currently being cleaned up. If you need to store the object, you can do so (save it to Sqlite or CoreData).

  • The proxy method is called when the cache object is about to be cleaned up, in the following scenarios:

        • (void)removeObjectForKey:(id)key; Manually delete objects;
      1. The cache object exceeds the NSCache attribute limit. (countLimit and totalCostLimit)
      1. App will be called when it enters the background;
      1. The system issued a memory warning.
  • practice

#import "ViewController.h" @interface ViewController ()<NSCacheDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSCache *cache = [[NSCache alloc]init]; cache.name = @"testCache"; [cache setCountLimit:5]; cache.delegate = self; NSString *test = @"Hello NSCache"; [cache setObject:test forKey:@"Test"]; NSLog(@"objectForKey:%@",[cache objectForKey:@"Test"]); NSLog(@"name:%@",cache.name); for (int i = 0; i < 10; i++) { [cache setObject:[NSString stringWithFormat:@"WorldCost%d", i] forKey:[NSString stringWithFormat:@"HelloCost%d", i] cost:1]; NSLog(@"Add key:%@ value:%@ to Cache", [NSString stringWithFormat:@"HelloCost%d", i], [NSString stringWithFormat:@"WorldCost%d", i]); } // for (int i = 0; i < 10; i++) // { // [cache setObject:[NSString stringWithFormat:@"World%d", i] forKey:[NSString stringWithFormat:@"Hello%d", i]]; // NSLog(@"Add key:%@ value:%@ to Cache", [NSString stringWithFormat:@"Hello%d", i], [NSString stringWithFormat:@"World%d", i]); // } // for (int i = 0; i < 10; i++) // { // NSLog(@"Get value:%@ for key :%@", [cache objectForKey:[NSString stringWithFormat:@"Hello%d", i]], [NSString stringWithFormat:@"Hello%d", i]); // } //// [cache removeAllObjects]; // for (int i = 0; i < 10; i++) // { // NSLog(@"Get value:%@ for key:%@", [cache objectForKey:[NSString stringWithFormat:@"World%d", i]], [NSString stringWithFormat:@"World%d", i]); // } // NSLog(@"Test %@", test); - (void)cache:(NSCache *)cache willEvictObject:(nonnull id)obj {NSLog(@"Remove Object ") %@", obj); } @endCopy the code

Basic usage of YYCache

- (void)YYCacheSyncTest{NSString *value=@"I want to know who is LCJ?" ; NSString *key=@"key"; YYCache *yyCache=[YYCache cacheWithName:@"LCJCache"]; // write to cache according to key value [yyCache setObject:value forKey:key]; BOOL isContains=[yyCache containsObjectForKey:key]; BOOL isContains=[yyCache containsObjectForKey:key]; NSLog(@"containsObject : %@", isContains? @"YES":@"NO"); Id vuale=[yyCache objectForKey:key]; NSLog(@"value : %@",vuale); [yyCache removeObjectForKey:key]; [yyCache removeAllObjects]; } - (void)YYCacheAsyncTest{NSString *value=@"I want to know who is LCJ?" ; NSString *key=@"key"; YYCache *yyCache=[YYCache cacheWithName:@"LCJCache"]; Value [yyCache setObject:value forKey:key withBlock:^{NSLog(@"setObject sucess");}]; [yyCache containsObjectForKey:key withBlock:^(NSString * _Nonnull key, BOOL contains) { NSLog(@"containsObject : %@", contains?@"YES":@"NO"); }]; [yyCache objectForKey:key withBlock:^(NSString * _Nonnull key, NSString * _Nonnull key, id<NSCoding> _Nonnull object) { NSLog(@"objectForKey : %@",object); }]; [yyCache removeObjectForKey:key withBlock:^(NSString * _Nonnull key) {NSLog(@"removeObjectForKey %@",key); }]; / / remove all cache [yyCache removeAllObjectsWithBlock: ^ {NSLog (@ "removeAllObjects sucess");}]. / / remove all cache with progress [yyCache removeAllObjectsWithProgressBlock: ^ (int removedCount, int totalCount) { NSLog(@"removeAllObjects removedCount :%d totalCount : %d",removedCount,totalCount); } endBlock:^(BOOL error) { if(!error){ NSLog(@"removeAllObjects sucess"); }else{ NSLog(@"removeAllObjects error"); } }]; } - (void)YYCacheLurTest{ YYCache *yyCache=[YYCache cacheWithName:@"LCJCache1"]; [yyCache.memoryCache setCountLimit:10]; // Maximum number of cache data in memory [yycache.MemoryCache setCostLimit:1*1024]; [yycache.diskcache setCostLimit:10*1024]; [yycache.diskCache setCountLimit:10]; [yycache.diskCache setAutoTrimInterval:1]; For (int I =0; int I =0; i<100; NSString *value=@"I want to know who is LCJ?" ; NSString *key=[NSString stringWithFormat:@"key%d", I]; NSString *key=[NSString stringWithFormat:@"key%d", I]; [yyCache setObject:value forKey:key]; } NSLog(@"yyCache.memoryCache.totalCost:%lu",(unsigned long)yyCache.memoryCache.totalCost); NSLog(@"yyCache.memoryCache.costLimit:%lu",(unsigned long)yyCache.memoryCache.costLimit); NSLog(@"yyCache.memoryCache.totalCount:%lu",(unsigned long)yyCache.memoryCache.totalCount); NSLog(@"yyCache.memoryCache.countLimit:%lu",(unsigned long)yyCache.memoryCache.countLimit); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSLog(@"yyCache.diskCache.totalCost:%lu",(unsigned long)yyCache.diskCache.totalCost); NSLog(@"yyCache.diskCache.costLimit:%lu",(unsigned long)yyCache.diskCache.costLimit); NSLog(@"yyCache.diskCache.totalCount:%lu",(unsigned long)yyCache.diskCache.totalCount); NSLog(@"yyCache.diskCache.countLimit:%lu",(unsigned long)yyCache.diskCache.countLimit); for(int i=0 ; i<100; NSString *key=[NSString stringWithFormat:@"key%d", I]; id vuale=[yyCache objectForKey:key]; NSLog(@"key: % @value: %@",key,vuale); }}); } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self YYCacheLurTest]; }Copy the code