2012-07-25 204 views
0

我遇到問題,我需要將Documents子目錄的內容移動到Documents Directory的「根目錄」。 爲此,我想將子目錄的所有內容複製到Documents目錄,然後刪除我的子目錄。將目錄的內容複製到Documents目錄

NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"] 

這就是我如何獲取Documents目錄的路徑以及我的子目錄名爲inbox的路徑。

NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentinbox error:nil]; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

然後我創建一個包含子文件夾中所有文檔的數組,並初始化文件管理器。

現在我必須執行for循環,爲每個文檔將文檔從子目錄複製到文檔目錄。

for(int i=0;i<[inboxContents count];i++){ 
    //here there is the problem, I don't know how to copy each file 

我想使用moveItemAtPath方法,但我不知道如何獲取每個文件的路徑。

希望您能理解我的問題, 感謝您的幫助 NICCO

+0

moveItemAtPath不起作用,因爲您無法從應用程序包目錄中刪除文件。 – 2012-07-25 16:43:47

+0

@ H2CO3文件目錄不是捆綁包的一部分。 – Joe 2012-07-25 16:49:36

+0

@Joe對不起,對不起,我誤解了這個問題,出現的通常問題是無法寫入XXXX.app(它是*本身的包)。 – 2012-07-25 16:51:34

回答

2

您可以使用moveItemAtPath:toPath:error:如下。

NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"]; 

//Initialize fileManager first 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

//You should always check for errors 
NSError *error; 
NSArray *inboxContents = [fileManager contentsOfDirectoryAtPath:documentinbox error:&error]; 
//TODO: error handling if inboxContents is nil 

for(NSString *source in inboxContents) 
{ 
    //Create the path for the destination by appending the file name 
    NSString *dest = [documentsDirectory stringByAppendingPathComponent: 
         [source lastPathComponent]]; 

    if(![fileManager moveItemAtPath:source 
          toPath:dest 
          error:&error]) 
    { 
     //TODO: Handle error 
     NSLog(@"Error: %@", error); 
    } 
}