iOS中計算磁碟快取檔案夾的大小

來源:互聯網
上載者:User

標籤:suse   attr   contains   manager   磁碟   判斷   執行   rect   nsca   

SDWebImage架構中在自動做磁碟緩衝的過程中,底層實現了計算Cache的大小,架構的方法名稱是getSize,但方法不容易被人理解,我就從新寫了一下,附帶注釋

  基本思想: 1. 先取出的Cache,擷取該檔案的路徑

                2. 利用NSFileManager,取出該檔案下的所有子路徑返回一個數組

      3.遍曆數組,利用檔案的fileSize屬性,把每個子路徑下檔案的取出來累加,即為該檔案夾的大小

      注意: 注意檔案夾的隱藏檔案,會使得到的檔案大小出現偏差

             得到的大小為B,若是在蘋果手機中,需轉化M(需要除去(1000.0 * 1000.0))

 

 

// 擷取cache檔案夾路徑

    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    // 建立檔案管理者單粒(要想管理檔案,必須使用NSFileManager)

    NSFileManager *mgr = [NSFileManager defaultManager];

    

    // 擷取檔案夾所有子路徑數組:擷取多級目錄下檔案路徑

    NSArray *subpaths = [mgr subpathsAtPath:cachePath];

    

    // 遍曆

    int totalSize = 0;

    for (NSString *subPath in subpaths) {

    //拼接每一條子路徑

        NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];

        

        // 判斷是否是隱藏檔案(.DS為蘋果中的一種隱藏檔案),若是隱藏檔案,跳過該次執行,進入下次執行

        if ([filePath containsString:@".DS"]) continue;

        

        // 判斷是否是檔案夾

        BOOL isDirectory = NO;

  //如果檔案不存在或者為檔案夾,就跳過

        BOOL isExists = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];

        if (!isExists || isDirectory) continue;

        

        // 擷取檔案屬性(利用檔案的fileSize屬性)

       NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil];

        totalSize += [attr fileSize];

iOS中計算磁碟快取檔案夾的大小

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.