作為一個開發者,對於緩存的清理也是理所應當的需要的。這次就簡單的談一下iOS中對於緩存的清理方法。
我們清理緩存通常是在這三種方式下進行的:
(1)項目中的清理緩存按鈕
(2)點擊退出app按鈕時清理緩存
(3)手動殺死進程 (說明:我們使用蘋果手機時,大部分人並不喜歡每次都去點擊退出app按鈕。所以客戶就有了在我們手動殺死進程時,對app進行緩存清理的要求)
接下來我們就從這三種方面來分析iOS的清理緩存。
我們知道iOS應用是在沙箱(sandbox)中的,在文件讀寫權限上受到限制,只能在幾個目錄下讀寫文件:
- Documents:應用中用戶數據可以放在這里,iTunes備份和恢復的時候會包括此目錄
- tmp:存放臨時文件,iTunes不會備份和恢復此目錄,此目錄下文件可能會在應用退出后刪除
- Library/Caches:存放緩存文件,iTunes不會備份此目錄,此目錄下文件不會在應用退出刪除
項目中的清理緩存按鈕的代碼就不列出了(我們可以在視圖上直接添加Button,也可以在tableView上列出一個cell做清理緩存按鈕),下面我直接給出清理緩存的代碼
1、Caches目錄的緩存一
#pragma mark - ************* Get cache size(計算數據緩存)*************
- (NSString *)getCacheSize{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = nil;
paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSMutableString *cachepath = [paths objectAtIndex:0];
NSError *error = nil;
//文件夾下所有的目錄和文件大小
float cacheSize = 0.0f;
//fileList便是包含有該文件夾下所有文件的文件名及文件夾名的數組
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:cachepath error:&error];
BOOL isDir = NO;
//在上面那段程序中獲得的fileList中列出文件夾名
for (NSString *file in fileList) {
NSString *path = [cachepath stringByAppendingPathComponent:file];
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
//獲取文件屬性
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];//[[NSFileManager defaultManager] fileAttributesAtPath: path traverseLink: YES];
//獲取文件的創建日期
NSDate *modificationDate = (NSDate*)[fileAttributes objectForKey: NSFileModificationDate];
int timeSepearte = (int)[[NSDate date] timeIntervalSince1970]-(int)[modificationDate timeIntervalSince1970];
if (timeSepearte>(3*86400)) {
if ([fileManager isDeletableFileAtPath:path]) {
[fileManager removeItemAtPath:path error:nil];
}
}else{
if (isDir) {
cacheSize = cacheSize + [self fileSizeForDir:path];
}
}
isDir = NO;
}
NSString *cacheSizeString = @"";
if (cacheSize >1024*1024) {
float cacheSize_M = cacheSize/(1024*1024);
cacheSizeString = [NSString stringWithFormat:@"%.1f M",cacheSize_M];
}else if (cacheSize>1024&&cacheSize<1024*1024) {
float cacheSize_KB = cacheSize/(1024);
cacheSizeString = [NSString stringWithFormat:@"%.1f KB",cacheSize_KB];
}else{
float cacheSize_BYT = cacheSize/(1024);
cacheSizeString = [NSString stringWithFormat:@"%.1f B",cacheSize_BYT];
}
return cacheSizeString;
}
-(float)fileSizeForDir:(NSString*)path//計算文件夾下文件的總大小
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
float size =0;
NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
for(int i = 0; i<[array count]; i++)
{
NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
BOOL isDir;
if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
{
NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
size+= fileAttributeDic.fileSize;
}
else
{
[self fileSizeForDir:fullPath];
}
}
return size;
}
2、Cache目錄的緩存 二
#pragma mark - 計算緩存大小
- (NSString *)getCacheSize1
{
//定義變量存儲總的緩存大小
long long cacheSize = 0;
//01.獲取當前圖片緩存路徑
NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
//02.創建文件管理對象
NSFileManager *filemanager = [NSFileManager defaultManager];
//獲取當前緩存路徑下的所有子路徑
NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];
//遍歷所有子文件
for (NSString *subPath in subPaths) {
//1).拼接完整路徑
NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];
//2).計算文件的大小
long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];
//3).加載到文件的大小
cacheSize += fileSize;
}
float size_m = cacheSize/(1024*1024);
return [NSString stringWithFormat:@"%.2fM",size_m];
}
清理緩存:
- (void)cleanCache
{
//清理緩存
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *paths = nil;
paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSMutableString *cachepath = [paths objectAtIndex:0];
NSError *error = nil;
NSArray *fileList = [manager contentsOfDirectoryAtPath:cachepath error:&error];
for (NSString *file in fileList) {
NSString *path = [cachepath stringByAppendingPathComponent:file];
if ([manager isDeletableFileAtPath:path]) {
[manager removeItemAtPath:path error:nil];
}
}
}
3、NSUserDefaults (適合存儲輕量級的本地數據),存儲文件的清理
- (void)cleanCache
{
NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
NSDictionary *dictionary = [defatluts dictionaryRepresentation];
for(NSString *key in [dictionary allKeys]){
[defatluts removeObjectForKey:key];
[defatluts synchronize];
}
}
以上就是關於iOS緩存的內容。
這篇不錯的文章可以看下: