清除緩存在每一個應(yīng)用是一個很常見的功能,今天這里小結(jié)一下躲查。
將數(shù)據(jù)永久性的存儲我們稱為數(shù)據(jù)持久化,其本質(zhì)是將數(shù)據(jù)存儲到文件中译柏,放到本地镣煮,共手機使用。
由于緩存文件是存在APP沙盒文件中的鄙麦,所以我們要實現(xiàn)緩存的清除典唇,需要通過NSFileManager的API來對緩存的清除,
沙盒機制
沙盒是針對安裝到移動終端上的每一個APP單獨生成的文件夾胯府,存儲用戶的個性設(shè)置介衔,每一個用戶的內(nèi)容不同,只具有讀寫功能盟劫。
沙盒文件夾的幾個路徑文件夾
Documents文件夾
存放數(shù)據(jù)持久化文件,比如:通訊錄信息,備份時也備份該文件夾內(nèi)容,該文件夾內(nèi)容不能過大,否則無法上傳到AppStore
獲取方法
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"doo = %@",documentsPath);
Library文件夾
Library 包含了Documents夜牡,Preferences,tmp侣签。
Caches:存放緩存文件,下載的視頻,圖片,音頻,小說都在該文件夾下
Preferences:存放用戶偏好設(shè)置,比如:存儲用戶的用戶名和密碼
tmp:存放臨時文件,比如:下載的zip包,解壓之后將zip包刪除,將解壓內(nèi)容移到Caches文件夾下.
Caches獲取方法
NSString *cachesPath =? [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,? NSUserDomainMask, YES) firstObject];
NSLog(@"cachesPath = %@",cachesPath);
下面的代碼是可以封裝成一個 tool類
/**
*? 獲取緩存路徑
*
*? @return 緩存路徑
*/
+(NSString *)cachePath;
/**
*? 清除緩存
*/
+(BOOL)clearCache;
/**
*? 獲取緩存大小(單位:M)
*
*? @return 緩存大小
*/
+ (float)cacheSize;
/**
*? 獲取緩存大小,(以..kb/..M)形式獲取
*? 小于1M,以kb形式返回,大于1M,以M形式返回
*? @return 緩存大小+單位
*/
+(NSString *)cacheSizeFormat;
/**
*? 獲取緩存路徑
*
*? @return 緩存路徑
*/
+(NSString *)cachePath {
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
return cachesPath;
}
/**
*? 清除緩存
*/
+(BOOL)clearCache {
///創(chuàng)建文件管理類
NSFileManager *fileManager = [NSFileManager defaultManager];
///獲取路徑
NSString *path = [self cachePath];
BOOL result = [fileManager removeItemAtPath:path error:nil];
[self checkDirectory:path];
return result;
}
//檢查路徑
+(void)checkDirectory:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) {
[self createBaseDirectoryAtPath:path];
} else {
if (!isDir) {
NSError *error = nil;
[fileManager removeItemAtPath:path error:&error];
[self createBaseDirectoryAtPath:path];
}
}
}
+ (void)createBaseDirectoryAtPath:(NSString *)path {
__autoreleasing NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES
attributes:nil error:&error];
if (error) {
DebugLog(@"create cache directory failed, error = %@", error);
} else {
DebugLog(@"path = %@",path);
[self addDoNotBackupAttribute:path];
}
}
+ (void)addDoNotBackupAttribute:(NSString *)path {
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
[url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
if (error) {
DebugLog(@"error to set do not backup attribute, error = %@", error);
}
}
/**
*? 獲取緩存大小(單位:M)
*
*? @return 緩存大小
*/
+ (float)cacheSize {
NSString *directoryPath = [self cachePath];
BOOL isDir = NO;
unsigned long long total = 0;
if ([[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDir]) {
if (isDir) {
NSError *error = nil;
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:&error];
if (error == nil) {
for (NSString *subpath in array) {
NSString *path = [directoryPath stringByAppendingPathComponent:subpath];
NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:path
error:&error];
if (!error) {
total += [dict[NSFileSize] unsignedIntegerValue];
}
}
}
}
}
return total/(1024.0*1024.0);
}
/**
*? 獲取緩存大小,(以..kb/..M)形式獲取
*? 小于1M,以kb形式返回,大于1M,以M形式返回
*? @return 緩存大小+單位
*/
+(NSString *)cacheSizeFormat {
NSString *sizeUnitString;
float size = [self cacheSize];
if(size < 1)
{
size *= 1024.0;//小于1M轉(zhuǎn)化為kb
sizeUnitString = [NSString stringWithFormat:@"%.1fkb",size];
}
else{
sizeUnitString = [NSString stringWithFormat:@"%.1fM",size];
}
return sizeUnitString;
}
當然我們在APP 中有時也會加載webView,那個有時webView的緩存也要清除塘装,我們主要清除是Cookie
- (void)viewDidDisappear:(BOOL)animated {
? ?[super viewDidDisappear:animated];
_webView = nil;
[self cleanCacheAndCookie];
}
/**清除緩存和cookie*/
- (void)cleanCacheAndCookie{
//清除cookies
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]){
[storage deleteCookie:cookie];
}
//清除UIWebView的緩存
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURLCache * cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
[cache setDiskCapacity:0];
[cache setMemoryCapacity:0];
}