移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage。
但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯、购物、阅读类app的标配功能。
今天介绍的离线缓存功能的实现,主要分为缓存文件大小的获取、删除缓存文件的实现。
获取缓存文件的大小
由于缓存文件存在沙箱中,我们可以通过NSFileManager API来实现对缓存文件大小的计算。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#import <Foundation/Foundation.h> @interface CalculateFileSize : NSObject //单利
+ (instancetype)defaultCalculateFileSize;
- (float)fileSizeAtPath:(NSString*)path;
- (float)folderSizeAtPath:(NSString*)path;
- (void)clearCache:(NSString *)path; @end
#import "CalculateFileSize.h" @implementation CalculateFileSize
+ (instancetype)defaultCalculateFileSize { static CalculateFileSize *calculateFileSize = nil; @synchronized(self) { if (!calculateFileSize) { calculateFileSize = [[self alloc]init];; } } return calculateFileSize; }
- (float)fileSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if([fileManager fileExistsAtPath:path]){ long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize; return size/1024.0/1024.0; } return 0; }
- (float)folderSizeAtPath:(NSString *)path{ NSFileManager *fileManager = [NSFileManager defaultManager]; float folderSize; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { NSString *absolutePath = [path stringByAppendingPathComponent:fileName]; folderSize += [self fileSizeAtPath:absolutePath]; } return folderSize; } return 0; }
- (void)clearCache:(NSString *)path{ NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { NSString *absolutePath = [path stringByAppendingPathComponent:fileName]; [fileManager removeItemAtPath:absolutePath error:nil]; } } } @end
#import "CalculateFileSize.h" #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { CalculateFileSize *calculatefileSize = [CalculateFileSize defaultCalculateFileSize]; NSString *path = @"/Users/developer/Desktop/c - c++ 学习计划.xlsx"; float filSize = [calculatefileSize fileSizeAtPath:path]; NSLog(@"文件大小为%fM" ,filSize); } return 0; }
|