NSCache 基本上就是一個會自動移除對象來釋放內存的 NSMutableDictionary。無需響應內存警告或者使用計時器來清除緩存。惟一的不一樣之處是鍵對象不會像 NSMutableDictionary 中那樣被複制,這其實是它的一個優勢(鍵不須要實現 NSCopying 協議)。緩存
@property (assign) id<NSCacheDelegate>delegate;
cache對象的代理 , 用來即將清理cache的時候獲得通知安全
- (void)cache:(NSCache *)cache willEvictObject:(id)obj;
代理方法 , 這裏面不要對cache進行改動 , 若是對象obj須要被持久化存儲的話能夠在這裏進行操做app
這裏面有幾種狀況會致使該方法執行:性能
@property BOOL evictsObjectsWithDiscardedContent;
該屬性默認爲True , 表示在內存銷燬時丟棄該對象 。atom
@property NSUInteger totalCostLimit;
總成本數 , 用來設置最大緩存數量線程
// // TDFSetPhoneNumController.m // TDFLoginModule // // Created by doubanjiang on 2017/6/5. // Copyright © 2017年 doubanjiang. All rights reserved. // #import "viewController.h" @interface viewController () <NSCacheDelegate> @property (nonatomic ,strong) NSCache *cache; @end @implementation viewController - (void)viewDidLoad { [super viewDidLoad]; [self beginCache]; } - (void)beginCache { for (int i = 0; i<10; i++) { NSString *obj = [NSString stringWithFormat:@"object--%d",i]; [self.cache setObject:obj forKey:@(i) cost:1]; NSLog(@"%@ cached",obj); } } #pragma mark - NSCacheDelegate - (void)cache:(NSCache *)cache willEvictObject:(id)obj { //evict : 驅逐 NSLog(@"%@", [NSString stringWithFormat:@"%@ will be evict",obj]); } #pragma mark - Getter - (NSCache *)cache { if (!_cache) { _cache = [NSCache new]; _cache.totalCostLimit = 5; _cache.delegate = self; } return _cache; } @end
咱們會看到如下輸出代理
2018-07-31 09:30:56.485719+0800 Test_Example[52839:214698] object--0 cached 2018-07-31 09:30:56.485904+0800 Test_Example[52839:214698] object--1 cached 2018-07-31 09:30:56.486024+0800 Test_Example[52839:214698] object--2 cached 2018-07-31 09:30:56.486113+0800 Test_Example[52839:214698] object--3 cached 2018-07-31 09:30:56.486254+0800 Test_Example[52839:214698] object--4 cached 2018-07-31 09:30:56.486382+0800 Test_Example[52839:214698] object--0 will be evict 2018-07-31 09:30:56.486480+0800 Test_Example[52839:214698] object--5 cached 2018-07-31 09:30:56.486598+0800 Test_Example[52839:214698] object--1 will be evict 2018-07-31 09:30:56.486681+0800 Test_Example[52839:214698] object--6 cached 2018-07-31 09:30:56.486795+0800 Test_Example[52839:214698] object--2 will be evict 2018-07-31 09:30:56.486888+0800 Test_Example[52839:214698] object--7 cached 2018-07-31 09:30:56.486995+0800 Test_Example[52839:214698] object--3 will be evict 2018-07-31 09:30:56.487190+0800 Test_Example[52839:214698] object--8 cached 2018-07-31 09:30:56.487446+0800 Test_Example[52839:214698] object--4 will be evict 2018-07-31 09:30:56.487604+0800 Test_Example[52839:214698] object--9 cached
通過實驗咱們發現NSCache使用上性價比仍是比較高的,能夠在項目裏放心去用,能夠提高app的性能。code