天天看點

iOS 緩存清除方法

沒有固定的方法,你既然有做對應的緩存機制,這個機制就應該有清除緩存的方法。例如如果你使用某個第三方的圖檔庫,這個庫有緩存機制,那麼它就應該提供對應的清除緩存的方法。你調用對應的方法進行清除,如果你自己有用到資料庫,那麼你就應該清除資料庫裡面的資料等等。

指的是沙盒下的緩存檔案夾麼

移動應用在處理網絡資源時,一般都會做離線緩存處理,其中以圖檔緩存最為典型,其中很流行的離線緩存架構為SDWebImage。 但是,離線緩存會占用手機存儲空間,是以緩存清理功能基本成為資訊、購物、閱讀類app的标配功能。 今天介紹的離線緩存功能的實作,主要分為緩存檔案大小的擷取、删除緩存檔案的實作。 擷取緩存檔案的大小 由于緩存檔案存在沙箱中,我們可以通過NSFileManager API來實作對緩存檔案大小的計算。

檔案路徑:   NSString *cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];

計算單個檔案大小

1 2 3 4 5 6 7 8

+(

float

)fileSizeAtPath:(NSString *)path{

NSFileManager *fileManager=[NSFileManager defaultManager];

if

([fileManager fileExistsAtPath:path]){

long

long

size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;

return

size/1024.0/1024.0;

}

return

0;

}

計算目錄大小

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

+(

float

)folderSizeAtPath:(NSString *)path{

NSFileManager *fileManager=[NSFileManager defaultManager];

float

folderSize;

if

([fileManager fileExistsAtPath:path]) {

NSArray *childerFiles=[fileManager subpathsAtPath:path];

for

(NSString *fileName in childerFiles) {

NSString *absolutePath=[path stringByAppendingPathComponent:fileName];

folderSize +=[FileService fileSizeAtPath:absolutePath];

}

//SDWebImage架構自身計算緩存的實作

folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;

return

folderSize;

}

return

0;

}

清理緩存檔案 同樣也是利用NSFileManager API進行檔案操作,SDWebImage架構自己實作了清理緩存操作,我們可以直接調用。

1 2 3 4 5 6 7 8 9 10 11 12

+(

void

)clearCache:(NSString *)path{

NSFileManager *fileManager=[NSFileManager defaultManager];

if

([fileManager fileExistsAtPath:path]) {

NSArray *childerFiles=[fileManager subpathsAtPath:path];

for

(NSString *fileName in childerFiles) {

//如有需要,加入條件,過濾掉不想删除的檔案

NSString *absolutePath=[path stringByAppendingPathComponent:fileName];

[fileManager removeItemAtPath:absolutePath error:nil];

}

}

[[SDImageCache sharedImageCache] cleanDisk];   [[SDImageCache sharedImageCache] clearMemory];//添加這句話會清除頭像的緩存不好,用時注意,在更換頭像的時候清除之前頭像的緩存,可以用這句話,在設定頁最好不用

}