2012-02-10 105 views
10

我想將添加到名爲「includes」的文件夾中的文件複製到名爲「includes」的文檔目錄上的文件夾中。我得到resContents零值。爲什麼?謝謝iOS從主包中複製文件到文檔目錄

- (void)copyResources{ 

     NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"includes"]; 
     NSString *destPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"includes"]; 

     NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL]; 

     for (NSString* obj in resContents){ 
      NSError* error; 
      if (![[NSFileManager defaultManager] copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] toPath:[destPath stringByAppendingPathComponent:obj] 
        error:&error]) 
       NSLog(@"Error: %@", error);; 
     } 

    } 

回答

6

您應該將您的includes文件夾添加到您的Xcode項目中作爲文件夾引用而不是組。

組只是爲了保持組織結構而不是提供文件夾結構,因此當複製到設備時,所有文件都會在同一級別結束。

+0

太棒了,工作!謝謝 – Jaume 2012-02-10 15:47:25

2

看看你的編譯的應用程序包。

通常,XCode生成的包是平的。這意味着雖然您添加的資源文件將被複制到該包中,但您創建的任何目錄都不會,因此資源路徑中沒有「包含」目錄。因此,您的源內容將爲零。所以在你的情況下,嘗試只使用`NSString * sourcePath = [[NSBundle mainBundle] resourcePath];

編輯:好吧,很明顯,添加文件夾引用也適用(信貸給Ignacio Inglese)。

+0

好的,但列出了所有文件,包括.nib和plists!我只需要選擇特定文件夾中的文件。不可能? – Jaume 2012-02-10 15:37:15

+0

這是一個扁平的結構。 – twilson 2012-02-10 15:40:58

+0

@Jaume那麼你將不得不選擇你需要的文件(可能通過一個公共的擴展名,或者在你的代碼中保留一個文件名列表)。 – 2012-02-10 15:48:18

相關問題