iOS 开发~项目常用,经典内容收集ios相关点iOS 开发每天分享优质文章

iOS编程之缓存清除以及文件操作等

2017-01-09  本文已影响2669人  张不二01
1,SDWebImage图片缓存

这里简单讲解以下SDWebImage图片缓存大小计算以及清理缓存的方法

//计算缓存大小
NSUInteger size = [SDImageCache sharedImageCache].getSize;
double displaySize = size/ 1000.0 /1000.0;
NSLog(@"%.2f-------",displaySize);
[[SDImageCache sharedImageCache] clearDisk];
2,用NSFileManager自助计算缓存文件夹内的缓存

想要用NSFileManager清除缓存需要了解NSFileManager的基本操作,所以我们先讲解一下这个类的一些基本方法

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSDictionary *attrs = [fileManager attributesOfItemAtPath:cachePath error:&error];
NSLog(@"%@", attrs);
{
    NSFileOwnerAccountID : 501,
    NSFileSystemFileNumber : 6907377,
    NSFileExtensionHidden : 0,
    NSFileSystemNumber : 16777221,
    NSFileSize : 170,//这个文件夹大小不是我们需要的所有文件的大小
    NSFileGroupOwnerAccountID : 20,
    NSFilePosixPermissions : 493,
    NSFileCreationDate : 2017-01-08 11:07:18 +0000,
    NSFileType : NSFileTypeDirectory,
    NSFileGroupOwnerAccountName : staff,
    NSFileReferenceCount : 5,
    NSFileModificationDate : 2017-01-09 12:14:00 +0000
}
NSArray *directContents = [fileManager contentsOfDirectoryAtPath:cachePath error:&error];
NSArray *AllContents = [fileManager subpathsAtPath:cachePath];
BOOL isDirectory = NO;
BOOL exists = [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
__block NSInteger size = 0;
NSArray *AllContents = [fileManager subpathsAtPath:cachePath];
if (!error) {
    [AllContents enumerateObjectsUsingBlock:^(NSString *subPath, NSUInteger idx, BOOL * _Nonnull stop) {
        //注意属性必须通过全路径
        NSString *fullPath = [cachePath stringByAppendingPathComponent:subPath];

        BOOL isDirectory = NO;
        BOOL exists = [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
        
        if (!isDirectory) {
            //这个是文件,是文件的时候才需要计算大小
            NSInteger biteSize = [[fileManager attributesOfItemAtPath:fullPath error:nil][NSFileSize] integerValue];
            size += biteSize;
        }
    }];
    NSLog(@"%ld", (long)size);
}
3,用NSFileManager清除缓存
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
[fileManager removeItemAtPath:cachePath error:nil];
上一篇 下一篇

猜你喜欢

热点阅读