NSCache

什麼是NSCache?

NSCache是蘋果提供的一套緩存機制,主要用於內存緩存管理方面;

在沒有引入NSCache之前,我們要管理緩存,都是使用的NSMutableDictionary來管理,如:// 定義下載操作緩存池
@property (nonatomic, strong) NSMutableDictionary *operationCache;
// 定義圖片緩存池
@property (nonatomic, strong) NSMutableDictionary *imageCache;

然而,使用NSMutableDictionary來管理緩存是有些不妥的, 知道多線程操作原理的開發者都明白, NSMutableDictionary在線程方面來說是不安全,這也是蘋果官方文檔明確說明了的,而如果使用的是NSCache,那就不會出現這些問題.所以接下來我們先看看二者的區別:

&1 NSCache和NSMutableDictionary的相同點與區別:

相同點:
NSCache和NSMutableDictionary功能用法基本是相同的。

區別:
NSCache是線程安全的,NSMutableDictionary線程不安全 NSCache線程是安全的,Mutable開發的類一般都是線程不安全的
當內存不足時NSCache會自動釋放內存(所以從緩存中取數據的時候總要判斷是否爲空)
NSCache可以指定緩存的限額,當緩存超出限額自動釋放內存 緩存限額:
緩存數量 @property NSUInteger countLimit;
緩存成本 @property NSUInteger totalCostLimit;
蘋果給NSCache封裝了更多的方法和屬性,比NSMutableDictionary的功能要強大很多
2.代碼演示:

先定義緩存池,並懶加載初始化:

import “ViewController.h”

@interface ViewController ()

// 定義緩存池
@property (nonatomic, strong) NSCache *cache;
@end

@implementation ViewController
- (NSCache *)cache {
if (_cache == nil) {
_cache = [[NSCache alloc] init];
// 緩存中總共可以存儲多少條
_cache.countLimit = 5;
// 緩存的數據總量爲多少
_cache.totalCostLimit = 1024 * 5;
}
return _cache;
}

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //添加緩存數據
    for (int i = 0; i < 10; i++) {
    [self.cache setObject:[NSString stringWithFormat:@”hello %d”,i] forKey:[NSString stringWithFormat:@”h%d”,i]];
    NSLog(@”添加 %@”,[NSString stringWithFormat:@”hello %d”,i]);
    }

    //輸出緩存中的數據
    for (int i = 0; i < 10; i++) {
    NSLog(@”%@”,[self.cache objectForKey:[NSString stringWithFormat:@”h%d”,i]]);
    }

}
控制檯輸出結果爲: 控制檯輸出結果

通過輸出結果可以看出:

1.當我們使用NSCache來創建緩存池的時候,我們可以很靈活的設置緩存的限額, 2.當程序中的個數超過我們的限額的時候,會先移除最先創建的 3.如果已經移除了,那麼當我們輸出緩存中的數據的時候,就只剩下後面創建的數據了;
3. 演示NSCache的代理方法

先設置代理對象: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //設置NSCache的代理 self.cache.delegate = self; 調用代理方法: 這裏我僅用一個方法來演示:

 //當緩存被移除的時候執行
     - (void)cache:(NSCache *)cache willEvictObject:(id)obj{
    NSLog(@"緩存移除  %@",obj);
   }

輸出結果爲: 輸出結果

通過結果可以看出: NSCache的功能要比NSMutableDictionary的功能要強大很多很多;

4.當遇到內存警告的時候,

代碼演示:

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    //當收到內存警告,清除內存
    [self.cache removeAllObjects];
    //輸出緩存中的數據
    for (int i = 0; i < 10; i++) {
    NSLog(@”%@”,[self.cache objectForKey:[NSString stringWithFormat:@”h%d”,i]]);
    }
    }
    控制檯輸出結果: 收到內存警告 通過結果可以看出: 當收到內存警告之後,清除數據之後,NSCache緩存池中所有的數據都會爲空!

5.當收到內存警告,調用removeAllObjects 之後,無法再次往緩存池中添加數據

代碼演示:

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    //當收到內存警告,調用removeAllObjects 之後,無法再次往緩存中添加數據
    [self.cache removeAllObjects];
    //輸出緩存中的數據
    for (int i = 0; i < 10; i++) {
    NSLog(@”%@”,[self.cache objectForKey:[NSString stringWithFormat:@”h%d”,i]]);
    }
    }

// 觸摸事件, 以便驗證添加數據
- (void)touchesBegan:(NSSet

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章