2010-07-14 201 views
8

我試圖在第一次啓動時將一些文件從我的應用程序包複製到文檔目錄。我有第一次啓動的檢查,但爲了清楚起見,它們未包含在代碼段中。問題是,我複製到文檔目錄(已經存在),並在文件中,它指出:iPhone(iOS):將文件從主包複製到文檔文件夾錯誤

dstPath不得先於操作存在。

什麼是我直接複製到文檔根目錄的最佳方法?我想這樣做的原因是爲了允許iTunes文件共享支持。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"]; 

    NSLog(@"\nSource Path: %@\nDocuments Path: %@", sourcePath, documentsDirectory); 

    NSError *error = nil; 

    if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error]){ 
    NSLog(@"Default file successfully copied over."); 
    } else { 
    NSLog(@"Error description-%@ \n", [error localizedDescription]); 
    NSLog(@"Error reason-%@", [error localizedFailureReason]); 
    } 
    ... 
    return YES; 
} 

感謝

回答

11

你的目標路徑必須包含項目的名稱被複制,而不僅僅是文件夾。嘗試:

if([[NSFileManager defaultManager] copyItemAtPath:sourcePath 
      toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"] 
      error:&error]){ 
... 

編輯:對不起誤解了你的問題。不知道是否有更好的選項,然後迭代文件夾內容並單獨複製每個項目。如果你的目標的iOS4可以使用NSArray的-enumerateObjectsUsingBlock:功能爲:

NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL]; 
[resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) 
    { 
     NSError* error; 
     if (![[NSFileManager defaultManager] 
        copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
        toPath:[documentsDirectory stringByAppendingPathComponent:obj] 
        error:&error]) 
      DLogFunction(@"%@", [error localizedDescription]); 
    }]; 

附:如果您無法使用塊,你可以使用快速列舉:

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

for (NSString* obj in resContents){ 
    NSError* error; 
    if (![[NSFileManager defaultManager] 
       copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
       toPath:[documentsDirectory stringByAppendingPathComponent:obj] 
       error:&error]) 
      DLogFunction(@"%@", [error localizedDescription]); 
    } 
+0

感謝您的迴應,但這不是我想要做的。我想要做的是將Populator文件夾的內容複製到目錄根目錄(而不是文件根目錄中名爲Populator的文件夾)。你所說的要做的確有用,但不是我想要達到的。 – Jack 2010-07-14 12:53:42

+0

非常感謝,誤解幾乎肯定是我的錯。我將這個代碼用於iPad應用程序,因此將針對iOS 3.2,儘管最終這將支持iOS4。感謝您的代碼,任何想法如何讓它爲3.2(無塊)工作? – Jack 2010-07-14 13:25:34

+1

我已經使用快速枚舉添加了代碼。塊解決方案更多的是鍛鍊自己 - 塊對我來說是一個新概念。 – Vladimir 2010-07-14 13:34:08

6

一張紙條:
沒有問題didFinishLaunchingWithOptions冗長的操作:是一個概念上的錯誤。 如果這個副本花費太多時間,看門狗會殺了你。 在輔助線程或NSOperation中啓動它... 我個人使用一個計時器過程。

相關問題