SoFunction
Updated on 2025-04-12

How to get the size of the cached file and clear the cached file

When mobile applications process network resources, they generally perform offline cache processing, among which image cache is the most typical, and the most popular offline cache framework is SDWebImage.

However, offline cache will occupy the storage space of your phone, so the cache cleaning function has basically become a standard feature for information, shopping, and reading apps.

The implementation of offline caching functions introduced today is mainly divided into the implementation of obtaining cache file sizes and clearing cache files.

1. Get the cache file size

-( float )readCacheSize
{
NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
return [ self folderSizeAtPath :cachePath];
}

Since the cached files are in the sandbox, we can use the NSFileManager API to calculate the cached file size.

// traverse the folder to obtain the folder size, how much M is returned- ( float ) folderSizeAtPath:( NSString *) folderPath{
NSFileManager * manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath :folderPath]) return 0 ;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
NSString * fileName;
long long folderSize = 0 ;
while ((fileName = [childFilesEnumerator nextObject]) != nil ){
//Get full path of fileNSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
folderSize += [ self fileSizeAtPath :fileAbsolutePath];
}
return folderSize/( 1024.0 * 1024.0);
}
// Calculate the size of a single file- ( long long ) fileSizeAtPath:( NSString *) filePath{
NSFileManager * manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath :filePath]){
return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
}
return 0;
}

2. Clear the cache

- (void)clearFile
{
NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
//NSLog ( @"cachpath = %@" , cachePath);
for ( NSString * p in files) {
NSError * error = nil ;
//Get full path of fileNSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
[[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
}
}
//Read cache sizefloat cacheSize = [self readCacheSize] *1024;
 = [NSString stringWithFormat:@"%.2fKB",cacheSize];
}

The above is the method of IOS to obtain the size of cached files and clear cached files that IOS introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!