2010-07-14 200 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中启动它... 我个人使用一个计时器过程。

相关问题