技术iOS -- Demoios 知识小集

应用中清除缓存的相关处理

2015-11-09  本文已影响3708人  Tuberose


    // 这里打印出来的单位是Mb
    CYLog(@"%f", [SDImageCache sharedImageCache].getSize / 1000.0 / 1000.0);
    // 拿到沙盒的路径
    CYLog(@"%@", NSTemporaryDirectory());


    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 先拿到caches文件夹路径(它返回的是数组,所以取第一个)
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *file = [caches stringByAppendingPathComponent:@"default"];// 拼接的路径
//    NSString *file = [caches stringByAppendingString:@"default"];// 这是拼接的字符串
// 获得文件属性
// 它�只给你文件夹这个壳子有多大,没有给里面的文件有多大
NSDictionary *attrs = [mgr attributesOfItemAtPath:file error:nil];
    // 总大小
    NSInteger size = 0;

    // 文件路径
    // 先拿到caches文件夹路径(它返回的是数组,所以取第一个)
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *file = [caches stringByAppendingPathComponent:@"default"];// 拼接的路径
//    NSString *file = [caches stringByAppendingString:@"default"];// 这是拼接的字符串

    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];

    // 获得文件夹中的所有内容
//        NSArray *contents = [mgr contentsOfDirectoryAtPath:file error:nil];
//        它只能获得它当前文件夹的内容,不能往里面深挖,这里不用它
//        subpaths 获取文件夹里面文件的子路径,什么文件都能拿到了(文件夹能拿到,文件夹里面的文件也能拿到)
//        所以用subpaths就是做好的,只有给我们一个最根的文件夹,我们就能找到里面所有的文件,不需要一遍一遍递归去找了
    NSArray *subpaths = [mgr subpathsAtPath:file];
    for (NSString *subpath in subpaths) {
        // 获得全路径
        NSString *fullSubpath = [file stringByAppendingPathComponent:subpath];
        // 获得文件属性
        NSDictionary *attrs = [mgr attributesOfItemAtPath:fullSubpath error:nil];
//        size += [attrs[NSFileSize] integerValue];
        size += attrs.fileSize;
    }
    // 总大小
    NSInteger size = 0;

    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *file = [caches stringByAppendingPathComponent:@"default"];

    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];

    // 获得文件夹中的所有内容
    // enumerator遍历器,可以通过for..in..遍历所有的子路径
    NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:file];
    for (NSString *subpath in enumerator) {
        // 获得全路径
        NSString *fullSubpath = [file stringByAppendingPathComponent:subpath];
        // 获得文件属性
        NSDictionary *attrs = [mgr attributesOfItemAtPath:fullSubpath error:nil];
//        size += [attrs[NSFileSize] integerValue];
//       通过key直接取出来
        size += attrs.fileSize;
    }
- (NSUInteger)getSize {
    __block NSUInteger size = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
            NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
    });
    return size;
}


#import <Foundation/Foundation.h>

@interface NSString (CYExtension)
- (NSInteger)fileSize;
@end
#import "NSString+CYExtension.h"

@implementation NSString (CYExtension)
// 判断一个路径是文件夹 or 文件
//    [[mgr attributesOfItemAtPath:self error:nil].fileType isEqualToString:NSFileTypeDirectory];

- (NSInteger)fileSize
{
    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 是否为文件夹
    BOOL isDirectory = NO;
    // 这个路径是否存在
    BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory];
    // 路径不存在
    if (exists == NO) return 0;

    if (isDirectory) { // 文件夹
        // 总大小
        NSInteger size = 0;
        // 获得文件夹中的所有内容
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
        for (NSString *subpath in enumerator) {
            // 获得全路径
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
            // 获得文件属性
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
        return size;
    } else { // 文件
        return [mgr attributesOfItemAtPath:self error:nil].fileSize;
    }
}
@end

        // 计算大小
        dispatch_sync(dispatch_get_global_queue(0, 0), ^{
            // 计算缓存大小
            NSString *cacheFile = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"default"];
            NSString *text = [NSString stringWithFormat:@"清除缓存(%1.fMB)",cacheFile.fileSize / 1000.0 / 1000.0] / 1000.0];

            // 回到主线程
            dispatch_sync(dispatch_get_main_queue(), ^{
                self.textLabel.text = text;
            });
        });
/** 缓存路径 */
#define CYCacheFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"default"]
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.textLabel.text = @"清除缓存";

        // 禁止点击事件
        self.userInteractionEnabled = NO;

        // 右边显示圈圈
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [loadingView startAnimating];
        self.accessoryView = loadingView;

        // 计算大小
        [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
            // 计算缓存大小
            NSInteger size = CYCacheFile.fileSize;
            NSString *text = [NSString stringWithFormat:@"清除缓存(%1.fMB)",size / 1000.0 / 1000.0] / 1000.0];

            // 回到主线程
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.textLabel.text = text;
                self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                self.accessoryView = nil;// accessoryView的优先级是高于UITableViewCellAccessoryDisclosureIndicator(没有指针指针就挂了)
                // 允许点击事件
                self.userInteractionEnabled = YES;
            }];
        }];
    }
    return self;
}
// 计算大小
        [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
            // 计算缓存大小
            NSInteger size = CYCacheFile.fileSize;
            CGFloat unit = 1000.0;
            NSString *sizeText = nil;
            if (size >= unit * unit * unit) { // >= 1GB
                sizeText = [NSString stringWithFormat:@"%.1fGB", size / unit / unit / unit];
            } else if (size >= unit * unit) { // >= 1MB
                sizeText = [NSString stringWithFormat:@"%.1fMB", size / unit / unit];
            } else if (size >= unit) { // >= 1KB
                sizeText = [NSString stringWithFormat:@"%.1fKB", size / unit];
            } else { // >= 0B
                sizeText = [NSString stringWithFormat:@"%zdB", size];
            }
            NSString *text = [NSString stringWithFormat:@"%@(%@)", CYDefaultText, sizeText];
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中(你一点击,我就取消选中,那样的话,cell默认的灰色就不见了)
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)clearCache
{
    [SVProgressHUD showWithStatus:@"正在清除缓存" maskType:SVProgressHUDMaskTypeBlack];

    [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
        [[NSFileManager defaultManager] removeItemAtPath:CYCacheFile error:nil];

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [SVProgressHUD showSuccessWithStatus:@"清除成功"];

            self.textLabel.text = CYDefaultText;

            // 禁止点击事件
            self.userInteractionEnabled = NO;
        }];
    }];
}
 // 清除缓存(这个方法是:你直接传一个行号给我,我返回这一行对应的cell给你,然后调用clearCache:方法就行了)
    CYClearCacheCell *cell = (CYClearCacheCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell clearCache];


static NSString * const CYClearCacheCellId = @"clearCache";
static NSString * const CYOtherCellId = @"other";
static NSString * const CYThirdCellId = @"third";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) { // 清除缓存的cell
        CYClearCacheCell *cell = [tableView dequeueReusableCellWithIdentifier:CYClearCacheCellId];
        [cell updateStatus];
        return cell;
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        return [tableView dequeueReusableCellWithIdentifier:CYThirdCellId];
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CYOtherCellId];
        cell.textLabel.text = [NSString stringWithFormat:@"%zd - %zd", indexPath.section, indexPath.row];
        return cell;
    }
}
- (void)updateStatus
{
    if (self.accessoryView == nil) return;

    // 让圈圈继续旋转
    UIActivityIndicatorView *loadingView = (UIActivityIndicatorView *)self.accessoryView;
    [loadingView startAnimating];
}

#import "CYSettingViewController.h"
#import <SDImageCache.h>
#import "CYClearCacheCell.h"
#import "CYThirdCell.h"

@interface CYSettingViewController ()

@end

@implementation CYSettingViewController

static NSString * const CYClearCacheCellId = @"clearCache";
static NSString * const CYOtherCellId = @"other";
static NSString * const CYThirdCellId = @"third";

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"设置";
    self.view.backgroundColor = CYCommonBgColor;

    [self.tableView registerClass:[CYClearCacheCell class] forCellReuseIdentifier:CYClearCacheCellId];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CYOtherCellId];
    [self.tableView registerClass:[CYThirdCell class] forCellReuseIdentifier:CYThirdCellId];

    // 设置内边距(-25代表:所有内容往上移动25)
    self.tableView.contentInset = UIEdgeInsetsMake(CYCommonMargin - 35, 0, 0, 0);
}

#pragma mark - <数据源>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) { // 清除缓存的cell
        CYClearCacheCell *cell = [tableView dequeueReusableCellWithIdentifier:CYClearCacheCellId];
        [cell updateStatus];
        return cell;
    } else if (indexPath.section == 1 && indexPath.row == 2) {
        return [tableView dequeueReusableCellWithIdentifier:CYThirdCellId];
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CYOtherCellId];
        cell.textLabel.text = [NSString stringWithFormat:@"%zd - %zd", indexPath.section, indexPath.row];
        return cell;
    }
}

#pragma mark - <代理>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // 清除缓存
    CYClearCacheCell *cell = (CYClearCacheCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell clearCache];
}
@end
#import <UIKit/UIKit.h>

@interface CYClearCacheCell : UITableViewCell

- (void)clearCache;
/**
 * 更新状态
 */
- (void)updateStatus;
@end
#import "CYClearCacheCell.h"
#import <SVProgressHUD.h>

/** 缓存路径 */
#define CYCacheFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"default"]

static NSString * const CYDefaultText = @"清除缓存";

@implementation CYClearCacheCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.textLabel.text = CYDefaultText;

        // 禁止点击事件
        self.userInteractionEnabled = NO;

        // 右边显示圈圈
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [loadingView startAnimating];
        self.accessoryView = loadingView;

        // 计算大小
        [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
            // 计算缓存大小
            NSInteger size = CYCacheFile.fileSize;
            CGFloat unit = 1000.0;
            NSString *sizeText = nil;
            if (size >= unit * unit * unit) { // >= 1GB
                sizeText = [NSString stringWithFormat:@"%.1fGB", size / unit / unit / unit];
            } else if (size >= unit * unit) { // >= 1MB
                sizeText = [NSString stringWithFormat:@"%.1fMB", size / unit / unit];
            } else if (size >= unit) { // >= 1KB
                sizeText = [NSString stringWithFormat:@"%.1fKB", size / unit];
            } else { // >= 0B
                sizeText = [NSString stringWithFormat:@"%zdB", size];
            }
            NSString *text = [NSString stringWithFormat:@"%@(%@)", CYDefaultText, sizeText];

            // 回到主线程
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.textLabel.text = text;
                self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                self.accessoryView = nil;// accessoryView的优先级是高于UITableViewCellAccessoryDisclosureIndicator(没有指针指针就挂了)
                // 允许点击事件
                self.userInteractionEnabled = YES;
            }];
        }];
    }
    return self;
}

- (void)updateStatus
{
    if (self.accessoryView == nil) return;

    // 让圈圈继续旋转
    UIActivityIndicatorView *loadingView = (UIActivityIndicatorView *)self.accessoryView;
    [loadingView startAnimating];
}

- (void)clearCache
{
    [SVProgressHUD showWithStatus:@"正在清除缓存" maskType:SVProgressHUDMaskTypeBlack];

    [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
        [[NSFileManager defaultManager] removeItemAtPath:CYCacheFile error:nil];

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [SVProgressHUD showSuccessWithStatus:@"清除成功"];

            self.textLabel.text = CYDefaultText;

            // 禁止点击事件
            self.userInteractionEnabled = NO;
        }];
    }];
}

@end
上一篇下一篇

猜你喜欢

热点阅读