標籤:
由於項目需求中要求計算出應用內的快取檔案的大小及清除工作,做了一個小小的模組提供給大家分享,隨便說句買蘋果還是選個16g以上的那樣媽媽就不會擔心你的記憶體不用夠用了哦!
// 清除本機快取檔案
+ (void)clearCacheFile
{
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
for (NSString *fileName in files)
{
NSError *error;
NSString *path = [cachPath stringByAppendingPathComponent:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
}
}
}
// 計算本機快取檔案大小
+ (double)getCacheFileSize
{
NSFileManager *fileManager = [NSFileManager defaultManager];
double fileSize = 0.0;
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [fileManager subpathsAtPath:cachPath];
for (NSString *fileName in files)
{
NSString *path = [cachPath stringByAppendingPathComponent:fileName];
if ([fileManager fileExistsAtPath:path])
{
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
fileSize += (double)([fileAttributes fileSize]);
}
}
return fileSize;
}
iOS 擷取本機快取檔案大小及清除