iOS将文件从主bundle复制到文档目录



我正试图将添加到名为"includes"的文件夹中的文件复制到documents目录中名为"includes"的一个文件夹中。

我得到resContents的零值。为什么?

- (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);;
        }
    }
}

您的Xcode项目应该将includes文件夹添加为文件夹引用,而不是

组只是为了保持事物的有序性,而不是提供文件夹结构,因此当复制到设备时,所有文件最终都在同一级别。

查看已编译的应用程序包。

通常,Xcode生成的捆绑包是扁平的。这意味着,尽管您添加的资源文件将被复制到捆绑包中,但您创建的任何目录都不会,因此在资源路径中没有"includes"目录。因此,您的源内容将为零。

因此,在您的情况下,尝试仅使用:

NSString *sourcePath = [[NSBundle mainBundle] resourcePath];

编辑:很明显,添加文件夹引用也有效(归功于Ignacio Inglese)。

相关内容

最新更新