在 iOS 應用開發中,幾乎 every 團隊都會面臨同一個問題:同一份數據反覆從服務端拉取,既浪費流量,又拖慢首屏。緩存機制正是為了解決這一矛盾而生——把已經取回來的響應留在本地,下次遇到相同請求時直接命中,讓界面在毫秒級完成渲染。
NSURLRequest 在發出請求時需要攜帶一個緩存策略參數,用來告訴系統這次請求應當如何對待本地已有的數據。共有六種取值:
// 取得當前應用的全局緩存對象
+ (NSURLCache *)sharedURLCache;
// 替換為自定義的緩存對象
+ (void)setSharedURLCache:(NSURLCache *)cache;
// 初始化緩存對象
// memoryCapacity:內存緩存上限
// diskCapacity:磁盤緩存上限
// path:磁盤緩存存放路徑
// 注意:內存緩存在 App 退出後清空,磁盤緩存則會保留
- (instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacity
diskCapacity:(NSUInteger)diskCapacity
diskPath:(nullable NSString *)path;
// 讀取某個請求對應的緩存
- (nullable NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
// 寫入指定請求的緩存
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse
forRequest:(NSURLRequest *)request;
// 刪除單個請求的緩存
- (void)removeCachedResponseForRequest:(NSURLRequest *)request;
// 清空全部緩存
- (void)removeAllCachedResponses;
// 刪除某個時間之後產生的緩存
- (void)removeCachedResponsesSinceDate:(NSDate *)date NS_AVAILABLE(10_10, 8_0);
// 容量與佔用量
@property NSUInteger memoryCapacity;
@property NSUInteger diskCapacity;
@property (readonly) NSUInteger currentMemoryUsage;
@property (readonly) NSUInteger currentDiskUsage;
下面的示例把緩存容量設置為 1MB,並通過按鈕重複加載同一個 URL,藉此觀察緩存是否生效。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSURLCache *urlCache;
@property (strong, nonatomic) NSURL *url;
@property (strong, nonatomic) NSMutableURLRequest *request;
- (IBAction)reloadWebView:(UIButton *)sender;
@end
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *paramURLAsString = @"https://blog.sina.com.cn/u/2526279194";
self.urlCache = [NSURLCache sharedURLCache];
[self.urlCache setMemoryCapacity:1 * 1024 * 1024]; // 內存緩存上限 1MB
self.url = [NSURL URLWithString:paramURLAsString];
self.request = [NSMutableURLRequest requestWithURL:self.url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0f];
[self.myWebView loadRequest:self.request];
}
首次加載時本地沒有任何副本,數據只能從網絡取得,同時系統會把響應寫入緩存。
- (IBAction)reloadWebView:(UIButton *)sender {
// 先主動查一次緩存
NSCachedURLResponse *response = [self.urlCache cachedResponseForRequest:self.request];
if (response != nil) {
NSLog(@"命中緩存,直接使用本地數據");
[self.request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
[self.myWebView loadRequest:self.request];
self.connection = nil;
NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:self.request
delegate:self
startImmediately:YES];
self.connection = newConnection;
}
借助 NSURLConnection 的代理方法,可以把一次請求經歷的每個階段都輸出到控制台:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"收到響應");
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse {
NSLog(@"即將發送請求");
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"接收數據,長度 = %lu", (unsigned long)[data length]);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse {
NSLog(@"即將寫入緩存");
return cachedResponse;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"請求完成");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"請求失敗");
}
@end
第一次點擊,日誌中出現了「即將寫入緩存」:
即將發送請求 收到響應 接收數據,長度 = 30047 接收數據,長度 = 3575 接收數據,長度 = 1482 即將寫入緩存 請求完成
第二次點擊,日誌變成:
命中緩存,直接使用本地數據 即將發送請求 收到響應 接收數據,長度 = 35104 請求完成
可以明顯看到「即將寫入緩存」不再出現,而拿到的數據長度正好等於第一次三段數據的累計之和。這說明第二次並沒有真正走網絡,而是直接讀取了內存中的副本。
緩存是把雙刃劍。對於新聞列表、配置項這類變化不頻繁的資源,適合讓系統按協議緩存;對於行情、實名認證結果等強時效數據,則應顯式指定忽略緩存或校驗新鮮度。此外,磁盤緩存路徑要放在可寫目錄(如 Library/Caches)下,避免 App 審核與數據備份方面的爭議。