萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 系統下刪除檔案的 3 種核心方法與封裝工具類

前言:沙盒機制下的檔案刪除

iOS App 僅能存取自身沙盒目錄。刪除檔案需使用 NSFileManager,注意權限、路徑正確性與錯誤處理。本文整理 3 種核心方法並提供生產級封裝類。

方法一:單檔刪除(最常用)


NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = @"/path/to/file.txt"; // 完整絕對路徑

NSError *error = nil;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];

if (success) {
    NSLog(@"刪除成功: %@", filePath);
} else {
    NSLog(@"刪除失敗: %@, 錯誤: %@", filePath, error.localizedDescription);
}

關鍵點:

  • 必須傳入 NSError** 獲取失敗原因(權限不足、檔案不存在、目錄非空等)
  • 回傳 BOOL 表示結果
  • 也可刪除目錄(需遞刪內容)

方法二:批次移動/刪除(遍歷目錄)

將 Documents 目錄下所有檔案移至 Caches(或刪除):


- (void)moveAllDocumentsToCaches {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    
    // 取得 Documents 與 Caches 路徑
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject];
    
    // 列舉目錄內容
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:docPath error:&error];
    if (!contents) {
        NSLog(@"列舉失敗: %@", error);
        return;
    }
    
    for (NSString *fileName in contents) {
        NSString *srcPath = [docPath stringByAppendingPathComponent:fileName];
        NSString *dstPath = [cachePath stringByAppendingPathComponent:fileName];
        
        // 移動(刪除來源)
        if (![fileManager moveItemAtPath:srcPath toPath:dstPath error:&error]) {
            NSLog(@"移動失敗: %@ -> %@, %@", srcPath, dstPath, error.localizedDescription);
        }
    }
}

方法三:使用 FCFileManager 簡化操作(第三方輕量庫)

FCFileManager 封裝常用操作,支援相對路徑、鏈式呼叫:


// 移動檔案
[FCFileManager moveItemAtPath:@"test.txt" toPath:@"tests/test.txt"];

// 刪除檔案
[FCFileManager removeItemAtPath:@"test.txt"];

// 其他常用
[FCFileManager copyItemAtPath:@"src" toPath:@"dst"];
[FCFileManager createDirectoryAtPath:@"folder"];
BOOL exists = [FCFileManager fileExistsAtPath:@"file.txt"];

安裝:CocoaPods `pod 'FCFileManager'` 或手動拖入源碼。

生產級封裝工具類:StorageManager

整合建立目錄、讀寫、刪除、存在性檢查、MD5 校驗:


// StorageManager.h
@interface StorageManager : NSObject

+ (instancetype)sharedManager;

// 路徑構建
- (NSString *)documentPath:(NSString *)subPath;
- (NSString *)cachePath:(NSString *)subPath;
- (NSString *)tmpPath:(NSString *)subPath;

// 核心操作
- (BOOL)writeData:(NSData *)data toPath:(NSString *)path;
- (NSData *)readDataFromPath:(NSString *)path;
- (BOOL)deleteFileAtPath:(NSString *)path;
- (BOOL)fileExistsAtPath:(NSString *)path;
- (NSDictionary *)fileAttributesAtPath:(NSString *)path;
- (NSString *)md5ForFileAtPath:(NSString *)path;

// 目錄操作
- (BOOL)createDirectoryAtPath:(NSString *)path;
- (NSArray *)listFilesAtPath:(NSString *)path;
- (BOOL)deleteDirectoryAtPath:(NSString *)path;

@end

// StorageManager.m 關鍵實現
- (BOOL)deleteFileAtPath:(NSString *)path {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error = nil;
    BOOL success = [fm removeItemAtPath:path error:&error];
    if (!success) {
        NSLog(@"[StorageManager] Delete failed: %@ - %@", path, error.localizedDescription);
    }
    return success;
}

- (NSString *)md5ForFileAtPath:(NSString *)path {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    if (!handle) return nil;
    
    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    
    constexpr size_t bufferSize = 1024 * 1024; // 1MB buffer
    while (YES) {
        NSData *chunk = [handle readDataOfLength:bufferSize];
        if (chunk.length == 0) break;
        CC_MD5_Update(&ctx, chunk.bytes, (CC_LONG)chunk.length);
    }
    [handle closeFile];
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &ctx);
    
    NSMutableString *md5 = [NSMutableString stringWithCapacity:32];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [md5 appendFormat:@"%02x", digest[i]];
    }
    return md5;
}

常見錯誤與避坑

❌ 路徑拼接錯誤
用 stringByAppendingPathComponent: 而非字串拼接,自動處理 `/`
❌ 忽略 NSError
無法診斷權限、鎖定、不存在等具體原因
❌ 刪除不存在的檔案視為錯誤
業務邏輯上常視為「已不存在 = 成功」,需判斷 error.code == NSFileNoSuchFileError
❌ 主執行緒大量檔案操作
阻塞 UI,放入背景隊列 dispatch_async(dispatch_get_global_queue(...), ^{ ... })

沙盒目錄速查

目錄取得方法備份策略用途
DocumentsNSDocumentDirectoryiCloud/iTunes 備份用戶產生、需持久化資料
Library/CachesNSCachesDirectory不備份可重建快取、圖片、資料庫
Library/PreferencesNSLibraryDirectory + Preferences備份NSUserDefaults、設定檔
tmpNSTemporaryDirectory()不備份、重啟可能清空臨時檔、下載中檔案
copyright © 萬盛學電腦網 all rights reserved