iOS 简单计算文件Cache的大小

来源:互联网 发布:天农教务网络管理系统 编辑:程序博客网 时间:2024/05/16 19:04

/*

 一般情况下这个计算Size的方法都安排在异步线程中的,所以需要用performSelector的方法回到主线程中刷新UI

 */


// 文件操作单粒

NSFileManger *fileManager = [NSFileManager defaultManager];


// 获取文件缓存路径

NSString *cachePath = [NSSearchPathForDirectoriesDomains(NSCachesDirectory,NSUserDomainMask,YES) ObjectAtIndex:0];


// 返回所有的文件名字

NSArray *files = [fileManager subpathsAtPath:cachepath];


// 总大小

long long fileSize = 0;


// 便利内部所有文件名字,然后和主Cache拼接在一起

for (NSString *p in files)

{

    // 拼接完整的路径

    NSString *path = [cachepath stringByAppendingPathComponent:p];


    if ([fileManager fileExistsAtPath:path])

    {

        // 根据绝对路径拼接出来的东西算出一个字典,内部有个FileSize拿出文件大小

        fileSize += [fileManager attributesOfItemAtPath:path error:nil].fileSize

    }


    // NSString+CPcatagory有一个方法把文件大小转换成KB

    self.cacheFileSize = [NSString stringWithFormat:@"%@",[NSString stringWithFile:fileSize]];


        // 回到主线程刷新UI  waitUntile  YES那么就是等线程结束的时候再进行方法,No的话就直接返回到主线程去刷新UI,不等子线程做完,如果当前线程是在主线程的话那么YES也就和NO一样直接返回到主线程刷新UI

        [self performSelectorOnMainThread:@selector(updateFileSizeLabel:) withObject:@(fileSize)waitUntil:YES];

}



// 给对应的cell增加fileSize的大小

- (void)updateFileSizeLabel:(NSNumber *)date{

    // 获取多少KB

    NSString *fileSize = [NSString stringWithFormat:@"%@",[NSString stringWithFileSize:date doubleValue]];

    // 通过settingsReader根据Key拿到indexpath

    NSIndexPath *indexPath = [self.settingReader indexPathForKey:@"ClearCache"];

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexpath];

    cell.detailTextLabel.text = fileSize;

    [cell.detailTextLabel setNeedsDisplay];

}



// NSString加的一个Category 用来计算fileSize的显示大小

+ (NSString*)stringWithFileSize:(unsigned long long)size

{

    if (size == 0)

    {

        return @"无缓存";

    }

    else if (size < 1000)

    {

        return [NSString stringWithFormat:@"%lluB", size];

    }

    else if(size < 1024 * 1024)

    {

        return [NSString stringWithFormat:@"%.2fKB", size / 1024.0];

    }

    else if(size < 1024 * 1024 * 1024)

    {

        return [NSString stringWithFormat:@"%.2fMB", size / (1024.0 * 1024)];

    }

    else if(size < 1024 * 1024 * 1024 * 1024ull)

    {

        return [NSString stringWithFormat:@"%.2fGB", size / (1024.0 * 1024 * 1024)];

    }

    else

    {

        return [NSString stringWithFormat:@"%.2fTB", size / (1024.0 * 1024 * 1024 * 1024)];

    }

}



0 0
原创粉丝点击