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

iOS 中複製與移動檔案的幾種做法

編輯:iOS 開發綜合

檔案搬移與複製在 iOS 中都是透過 NSFileManager 完成。以下整理單檔操作、批次搬移,以及一個第三方封裝工具。

一、單一檔案複製

if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) {
    NSLog(@"Copied successfully");
}

要移動(而非複製)單一檔案,把方法換成 moveItemAtPath:toPath:error: 即可。

二、批次搬移整個目錄

例如要把 Documents 下的所有檔案搬到 Caches:

- (void)moveAllDocs {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;

    NSString *sourceDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *destinationDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSArray *contents = [fileManager contentsOfDirectoryAtPath:sourceDirectory error:&error];
    for (NSString *sourceFileName in contents) {
        NSString *sourceFile = [sourceDirectory stringByAppendingPathComponent:sourceFileName];
        NSString *destFile = [destinationDirectory stringByAppendingPathComponent:sourceFileName];
        if (![fileManager moveItemAtPath:sourceFile toPath:destFile error:&error]) {
            NSLog(@"Error: %@", error);
        }
    }
}

要注意的是,跨「目錄」搬移在 iOS 沙盒內沒問題,但若目的地不存在,move 會失敗,因此需先確認目標目錄已建立(createDirectoryAtPath:withIntermediateDirectories:)。另外,這個範例只處理第一層,若來源含子目錄,需自行遞迴或用 enumeratorAtPath: 取得完整相對路徑。

三、FCFileManager

FCFileManager 是建構在 NSFileManager 之上的 iOS 檔案管理工具,把常用操作簡化成一行,並預設以文件目錄為基準,因此可以直接使用相對路徑(也能指定其他目錄)。

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

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

這類封裝工具的價值在於統一處理路徑組裝、錯誤檢查與目錄自動建立等重複瑣事。不過引入第三方套件前建議先確認其維護狀態與 iOS 版本相容性,早期這類工具在目錄基準的設計上與新版的 sandbox 結構未必吻合。

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