计算并清除缓存/获取文件路径
两个可以放一起
/**
* 获取文件地址
*/
- (NSString* )getFilePath:(NSString* )filePath
{
NSArray* array = [filePath componentsSeparatedByString:@"/"];
NSString* fileName = [array lastObject];
NSRange range = [filePath rangeOfString:fileName];
filePath = [filePath stringByReplacingCharactersInRange:range withString:@""];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
if ([[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
NSLog(@"成功");
}
}
filePath = [filePath stringByAppendingString:fileName];
return filePath;
}
然后就是计算缓存
/**
* 计算单个文件大小
*/
- (long long) fileSizeAtPath:(NSString*) filePath
{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath])
{
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
/**
* 计算缓存大小
*/
- (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){
NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
return folderSize/(1000.0*1000.0);
}
直接调用就OK
NSString *cacheAddress = [self getFilePath:[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Library/Caches"]]];
NSLog(@"文件地址%@",cacheAddress);
float cacheSize = [self folderSizeAtPath:cacheAddress];这个地方我只是试一试获取地址能不能用。。可以直接键入Cache文件的Path
NSLog(@"缓存大小%f",cacheSize);
清除缓存直接用SDWebimage内置方法就OK
[[SDImageCache sharedImageCache]clearDisk];
自己对于这方面还很迷惑,仅仅只是能copy一下解决一下需求而已,如果看官有好的讲解博客可以推荐一哈 蟹蟹