萬盛學電腦網

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

iOS 檔案移動完整指南:從基礎 API 到第三方封裝庫

前言:移動即複製+刪除的原子操作

iOS 沙盒中移動檔案使用 NSFileManager 的 moveItemAtPath:toPath:error:,底層同卷掛載時為元資料操作(極快),跨卷則為複製+刪除。本文涵蓋基礎用法、批次遷移、第三方庫封裝。

方法一:單檔移動(基礎 API)


NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;

BOOL success = [fileManager moveItemAtPath:@"/path/src.txt" 
                                    toPath:@"/path/dst.txt" 
                                     error:&error];

if (success) {
    NSLog(@"移動成功");
} else {
    NSLog(@"移動失敗: %@", error.localizedDescription);
}

注意:

  • 目標路徑**不能存在**同名檔案,否則失敗(需先刪除或改名)
  • 目標目錄必須存在,不會自動建立
  • 跨裝置(如 Documents → 外接裝置)會退化為複製+刪除,耗時較長

方法二:批次遷移整個目錄(Documents → Caches 範例)


- (void)migrateDocumentsToCaches {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error = nil;
    
    NSString *srcDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];
    NSString *dstDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject];
    
    NSArray *files = [fm contentsOfDirectoryAtPath:srcDir error:&error];
    if (!files) return;
    
    for (NSString *fileName in files) {
        NSString *src = [srcDir stringByAppendingPathComponent:fileName];
        NSString *dst = [dstDir stringByAppendingPathComponent:fileName];
        
        // 若目標已存在,先移除
        if ([fm fileExistsAtPath:dst]) {
            [fm removeItemAtPath:dst error:nil];
        }
        
        if (![fm moveItemAtPath:src toPath:dst error:&error]) {
            NSLog(@"遷移失敗 %@ -> %@: %@", src, dst, error.localizedDescription);
        }
    }
}

方法三:FCFileManager 輕量封裝庫

GitHub: marcoarment/FCFileManager


// 移動(自動處理目標目錄建立、相對路徑解析)
[FCFileManager moveItemAtPath:@"test.txt" toPath:@"subfolder/test.txt"];

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

// 複製
[FCFileManager copyItemAtPath:@"src" toPath:@"dst"];

// 建立目錄
[FCFileManager createDirectoryAtPath:@"deep/nested/folder"];

// 存在性檢查
BOOL exists = [FCFileManager fileExistsAtPath:@"file.txt"];

// 讀寫資料
NSData *data = [FCFileManager readDataAtPath:@"file.dat"];
[FCFileManager writeData:data toPath:@"file.dat"];

優勢:預設相對沙盒 Documents 目錄、鏈式語法、錯誤處理統一、程式碼極簡潔。

進階場景:安全移動(支援覆蓋、原子性、進度回調)


@interface SafeFileMover : NSObject

// 安全移動:目標存在則備份、支援進度、可取消
- (void)moveItemAtPath:(NSString *)srcPath 
                toPath:(NSString *)dstPath 
           overwrite:(BOOL)overwrite
            progress:(void (^)(float progress))progressBlock
           completion:(void (^)(BOOL success, NSError *error))completion;

@end

@implementation SafeFileMover

- (void)moveItemAtPath:(NSString *)srcPath 
                toPath:(NSString *)dstPath 
           overwrite:(BOOL)overwrite
            progress:(void (^)(float))progressBlock
           completion:(void (^)(BOOL, NSError *))completion {
    
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
        NSFileManager *fm = [NSFileManager defaultManager];
        NSError *error = nil;
        
        // 1. 目標存在處理
        if ([fm fileExistsAtPath:dstPath]) {
            if (!overwrite) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(NO, [NSError errorWithDomain:@"SafeMover" code:1 userInfo:@{NSLocalizedDescriptionKey: @"Destination exists"}]); 
                });
                return;
            }
            // 備份舊檔
            NSString *backup = [dstPath stringByAppendingString:@".bak"];
            [fm removeItemAtPath:backup error:nil];
            [fm moveItemAtPath:dstPath toPath:backup error:nil];
        }
        
        // 2. 確保目標目錄存在
        NSString *dstDir = [dstPath stringByDeletingLastPathComponent];
        [fm createDirectoryAtPath:dstDir withIntermediateDirectories:YES attributes:nil error:&error];
        
        // 3. 執行移動(同卷近乎瞬間)
        BOOL ok = [fm moveItemAtPath:srcPath toPath:dstPath error:&error];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(ok, error);
        });
    });
}

@end

常見錯誤代碼對照

錯誤代碼常數原因處理
4NSFileNoSuchFileError來源檔案不存在移動前檢查 exists
512NSFileWriteFileExistsError目標檔案已存在先刪除或設定 overwrite
513NSFileWriteNoPermissionError無寫入權限檢查沙盒權限、App Groups
516NSFileWriteOutOfSpaceError磁碟空間不足提示用戶清理空間
256NSFileReadUnknownError未知讀取錯誤重試、檢查檔案損壞

最佳實踐清單

  1. **永遠處理 NSError** —— 不要傳 `NULL`
  2. **移動前檢查來源存在、目標目錄存在**
  3. **大檔案/批次操作放背景隊列**
  4. **跨 App 共享檔案用 App Groups + NSFileCoordinator**
  5. **資料庫/核心資料檔案移動需關閉連接、斷開 WAL 模式**
  6. **單元測試覆蓋:存在、不存在、權限、空間不足、並發移動**
copyright © 萬盛學電腦網 all rights reserved