獲取和清除緩存

獲取某個(gè)文件夾的緩存本來我是以為NSDictionary<NSString *, id> *attributes = [manager attributesOfItemAtPath :filePath error:nil];
[attributes fileSize]; 直接獲取某個(gè)文件夾的數(shù)據(jù),其實(shí)是我太天真了,可以打印一下size ,完全對不上。這個(gè)時(shí)候需要用到 NSArray *childerFiles=[fileManager subpathsAtPath:folderPath]; 這個(gè)方法,特別提示是這個(gè)方法 深度遞歸去找所有的子文件夾和文件,這下再加起來就可以獲得總的size。

/* 
 * 只是計(jì)算某個(gè)(不是文件夾) 路徑的 size
 * 如果計(jì)算 文件夾 只會計(jì)算該文件夾的size  不會計(jì)算文件夾里面的size
 **/
+ (long long)fileSizeAtPath:( NSString *)filePath {
    
    NSFileManager *manager = [ NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        NSDictionary<NSString *, id> *attributes = [manager attributesOfItemAtPath :filePath error:nil];
        return [attributes fileSize];
    }
    return 0;
}

/*
 * 進(jìn)行深度遍歷 某個(gè)文件夾里面的所有的文件
 **/
+ (float)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath :folderPath])return 0;
    long long folderSize=0;
    if ([fileManager fileExistsAtPath:folderPath]) {
        
        /*
         * subpathsAtPath : This may be very expensive to compute for deep filesystem hierarchies, and should probably be avoided. 
         * 就是說會自己深度遍歷所有的 子文件
         **/
        NSArray *childerFiles=[fileManager subpathsAtPath:folderPath];
        for (NSString *fileName in childerFiles) {
            
            NSString *fileAbsolutePath=[folderPath stringByAppendingPathComponent:fileName];
            long long size=[self fileSizeAtPath:fileAbsolutePath];
            folderSize += size;
        }
    }
    return folderSize/1024.0/1024.0;
}
/*
 * 清楚某個(gè)路徑的cache
 **/
+(void)clearCache:(NSString *)path{
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            
            NSString *fileAbsolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:fileAbsolutePath error:nil];
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容