2012-02-10 132 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

相关问题