您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 清理應用緩存:定位 Caches 目錄並安全刪除

編輯:iOS 開發綜合

App 使用久了,快取圖片、離線數據、暫存檔案會不斷累積,佔用手機存儲空間。iOS 提供了「設定 → 通用 → iPhone 存儲」讓用戶自行清理,但更友善的做法是在 App 內提供一鍵清理入口,即時顯示可釋放的空間。

該清哪裡?

iOS 沙少说明三個主要目錄的定位:Documents 存放用戶產生的數據(iCloud 備份會包含它)、Library 存放非用戶數據,而 Library/Caches 才是真正該清的緩存——系統在空間不足時本來就會回收它,App 主動刪除是安全的。

清理實作

刪檔是 I/O 操作,務必放到子線程,完成後再回主線程更新界面。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                              NSUserDomainMask,
                                                              YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    NSLog(@"files : %ld", (unsigned long)[files count]);

    for (NSString *p in files) {
        NSError *error;
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }

    // 回到主線程更新 UI
    [self performSelectorOnMainThread:@selector(clearCacheSuccess)
                          withObject:nil
                       waitUntilDone:YES];
});

清理完成回調

- (void)clearCacheSuccess {
    NSLog(@"清理成功");
}

進階:先算出大小再清理

實務上通常會先計算快取佔用空間,讓用戶知道能清多少,再決定要不要清:

- (void)cacheSizeWithCompletion:(void (^)(unsigned long long))completion {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                                   NSUserDomainMask, YES) firstObject];
        unsigned long long totalSize = 0;
        NSFileManager *fm = [NSFileManager defaultManager];
        NSArray *files = [fm subpathsAtPath:cachesPath];
        for (NSString *path in files) {
            NSString *fullPath = [cachesPath stringByAppendingPathComponent:path];
            NSDictionary *attr = [fm attributesOfItemAtPath:fullPath error:nil];
            if (attr) totalSize += [attr fileSize];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(totalSize);
        });
    });
}

補充一點:NSCachesDirectory 下的內容可能在 App 未運行時被系統清掉,所以任何「刪掉就麻煩」的數據都不該放在這裡;反之,用戶數據若放進 Caches,反而可能被系統無預警清掉。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved