作為一個開發者,對于緩存的清理也是理所應當的需要的。這次就簡單的談一下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緩存的内容。
這篇不錯的文章可以看下:
iOS學習之IOS沙盒(sandbox)機制和檔案操作