Object-C 計(jì)算緩存大小
//計(jì)算緩存大小
- (CGFloat)calculateCache{
CGFloat folderSize = 0;
//獲取路徑
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
//獲取所有文件的數(shù)組
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
NSLog(@"文件數(shù):%ld",files.count);
for(NSString *path in files) {
NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
//累加
folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
}
//轉(zhuǎn)換為M為單位
CGFloat sizeM = folderSize /1024.0/1024.0;
return sizeM;
}
//清除緩存
- (void)removeCache{
//獲取路徑
NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
//返回路徑中的文件數(shù)組
NSArray*files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
NSLog(@"文件數(shù):%ld",[files count]);
for(NSString *p in files){
NSError*error;
NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
if([[NSFileManager defaultManager]fileExistsAtPath:path]) {
BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
if(isRemove) {
NSLog(@"清除成功");
} else {
NSLog(@"清除失敗");
}
}
}
}
Swift計(jì)算緩存
//統(tǒng)計(jì)緩存文件大小
func fileSizeOfCache()-> Int {
// 取出cache文件夾目錄 緩存文件都在這個(gè)目錄下 -->緩存目錄路徑
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
print(cachePath)
// 取出文件夾下所有文件數(shù)組
let fileArr = FileManager.default.subpaths(atPath: cachePath!)
//快速枚舉出所有文件名 計(jì)算文件大小
var size = 0
for file in fileArr! {
// 把文件名拼接到路徑中
let path = cachePath?.appending("/\(file)")
// 取出文件屬性
let floder = try! FileManager.default.attributesOfItem(atPath: path!)
// 用元組取出文件大小屬性
for (abc, bcd) in floder {
// 累加文件大小
if abc == FileAttributeKey.size {
size += (bcd as AnyObject).integerValue
}
}
}
let mm = size / 1024 / 1024
return mm
}
//刪除緩存文件
func clearCache() {
// 取出cache文件夾目錄 緩存文件都在這個(gè)目錄下
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
// 取出文件夾下所有文件數(shù)組
let fileArr = FileManager.default.subpaths(atPath: cachePath!)
// 遍歷刪除
for file in fileArr! {
let path = cachePath?.appending("/\(file)")
if FileManager.default.fileExists(atPath: path!) {
do {
try FileManager.default.removeItem(atPath: path!)
} catch {
}
}
}
}