APP 不可避免要與服務器進行交互,為了提高用戶體驗,緩存是必不可少的。以下是我的一點點想法,望斧正!
分類:
- 圖片緩存
- 數據緩存
- 文件緩存
圖片緩存
對于圖片下載,首選SDWebImage。它的緩存封裝的很好,足夠滿足使用。
一行代碼即可:
[[SDImageCache sharedImageCache] storeImage:image forKey:imageName toDisk:YES];
稍微看下原代碼:先把圖片存到NSCache,根據‘toDisk:’參數判斷是否存到磁盤?!甕ES’的話,會把圖片存到NSCachesDirectory下面。模擬器下是這樣:
.../Library/Caches/default/com.hackemist.SDWebImageCache.default
數據緩存
根據服務端response的cache-control來確定緩存策略。
創建NSMutableURLRequest的時候,不主動指定NSURLRequestCachePolicy,就會自動根據cache-control來緩存。不定義緩存大小,就會用默認的緩存大小。
這樣就可以由服務端統一管理,不需要區分android或iOS;更改緩存策略也不需要重新打包、發布。
當然,有些情況可以主動設定NSURLRequestCachePolicy、緩存大小,具體項目具體分析。
文件緩存
小文件等同于數據緩存,可以用NSCache;大文件自己放到NSCachesDirectory下面。
在官方文檔上看到,
The Caches directory is where you store cache files and other temporary data that your app can re-create as needed. This directory is located inside the Library directory.
Never store files at the top level of this directory: Always put them in a subdirectory named for your app or company. Your app is responsible for cleaning out cache data files when they are no longer needed. The system does not delete files from this directory.
To get the path to this directory use the NSCachesDirectory search path key with the NSUserDomainMask domain.
要注意不要把文件放到頂級目錄下(Never store files at the top level of this directory)。
不過,這個文檔說的是MAC的app;iOS找不到資料,不知道是不是這樣。。。
我測試了下,放到頂級目錄不會崩潰。不過最好不要放吧 ==!
官方文檔地址