2012-02-02 167 views
17

我正在使用名爲「temp」的iOS文檔文件夾分配包含從遠程URL下載的文件的子目錄。現在我需要將「temp」目錄及其所有內容複製到「main」文件夾(覆蓋先前創建的現有文件)。我知道如何處理文件,但如何複製整個目錄?謝謝iOS複製目錄包括子目錄

回答

30

您可以使用您熟悉並喜愛的目錄中相同的NSFileManager方法。例如:

if ([[NSFileManager defaultManager] fileExistsAtPath:pathToTempDirectoryInMain]) { 
    [[NSFileManager defaultManager] removeItemAtPath:pathToTempDirectoryInMain error:nil]; 
} 
NSError *copyError = nil; 
if (![[NSFileManager defaultManager] copyItemAtPath:pathToTempDirectory toPath:pathToTempDirectoryInMain error:&copyError]) { 
    NSLog(@"Error copying files: %@", [copyError localizedDescription]); 
} 
+0

太好了,謝謝! – Jaume 2012-02-03 09:55:20

+0

順便說一下,因爲它可能不是顯而易見的,您需要在運行此過程的用戶權限。 – Volomike 2016-03-14 16:20:54

5

NSFileManager方法removeItemAtPath:error:removeItemAtURL:error:copyItemAtPath:toPath:error:,並copyItemAtURL:toURL:error:方法處理目錄。

你也可以看看moveItemAtPath:toPath:error:moveItemAtURL:toURL:error:

+0

我使用了文件管理器的copyItemAtPath方法。是的,它確實複製了文件,但它保留了該級別的所有目錄。我希望將所有內容複製到目錄結構中。任何指針? – Alix 2015-08-31 19:05:42

+0

@Alix我是否運行'copyItemAtPath'或'moveItemAtPath',它會根據您指定的路徑名​​創建一個目錄,如果它不存在。因此,如果我創建/ tmp/src然後想要複製到/ tmp/dest或將其移動到/ tmp/dest中,如果我運行jrtc27的解決方案,它會自動刪除任何以前的/ tmp/dest,然後將其複製到的/ tmp/DEST。作爲另一個例子,假設我有/ tmp/Alix和/ home/alix/Documents這樣的文件夾,並且我想在其中放置一個Alix文件夾。很好 - 我只是將源設置爲/ tmp/Alix和dest。到/ home/alix/Documents/Alix。它會自動爲你創建Alix文件夾。 – Volomike 2016-03-14 16:58:47