清理緩存

  1. 只需要清理SDWebImage的圖片緩存,直接用SDImageCache單例的getSize方法
// 字節(jié)大小
    NSInteger byteSize = [SDImageCache sharedImageCache].getSize;
    // M大小  蘋果電腦計算不是1024
    double size = byteSize / 1000.0 / 1000.0;
    NSString *cacheSize = [NSString stringWithFormat:@"緩存大小(%.1fM)", size];
/**
 *  計算當前文件\文件夾的內容大小
 */
- (void)clearCache
{
    // 提醒
    UIActivityIndicatorView *circle = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [circle startAnimating];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:circle];
    
    // 清除緩存
    [[SDImageCache sharedImageCache] clearDisk];
    
    // 顯示按鈕
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清除緩存" style:0 target:self action:@selector(clearCache)];
    self.navigationItem.title = [NSString stringWithFormat:@"緩存大小(0M)"];
}

2.除了圖片還有其他緩存文件就需要刪除Library/Cache文件夾,搞一個NSString分類,給一個獲取文件夾、文件的所有大小的方法


- (NSInteger)fileSize
{
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 判斷是否為文件
    BOOL dir = NO;
    BOOL exists = [mgr fileExistsAtPath:self isDirectory:&dir];
    // 文件\文件夾不存在
    if (exists == NO) return 0;
    
    if (dir) { // self是一個文件夾
        // 遍歷caches里面的所有內容 --- 直接和間接內容
        NSArray *subpaths = [mgr subpathsAtPath:self];
        NSInteger totalByteSize = 0;
        for (NSString *subpath in subpaths) {
            // 獲得全路徑
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
            // 判斷是否為文件
            BOOL dir = NO;
            [mgr fileExistsAtPath:fullSubpath isDirectory:&dir];
            if (dir == NO) { // 文件
                totalByteSize += [[mgr attributesOfItemAtPath:fullSubpath error:nil][NSFileSize] integerValue];
            }
        }
        return totalByteSize;
    } else { // self是一個文件
        return [[mgr attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
    }
}

使用分類計算大小,直接刪除cache文件夾


- (void)fileOperation
{
    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 緩存路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    //文件大小
    NSInteger cacheSize = [caches fileSize];
    NSLog(@"%zd",cacheSize);

    // 刪除文件夾
    [mgr removeItemAtPath:caches error:nil];
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容