【问题标题】:Copy contents of a directory to Documents directory将目录的内容复制到 Documents 目录
【发布时间】:2012-07-24 04:06:52
【问题描述】:

我有一个问题,我需要将 Documents 子目录的内容移动到 Documents Directory 的“根目录”。 为此,我想将子目录的所有内容复制到 Documents 目录,然后删除我的子目录。

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"]

这就是我获取 Documents 目录的路径,以及我的名为 inbox 的子目录的路径。

 NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentinbox error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];

然后我创建一个包含子文件夹中所有文档的数组,并初始化文件管理器。

现在我必须实现 for 循环,为每个文档将文档从子目录复制到 Documents Directory。

for(int i=0;i<[inboxContents count];i++){
  //here there is the problem, I don't know how to copy each file

我想使用moveItemAtPath方法,但是不知道如何获取每个文件的路径。

希望你能理解我的问题, 感谢帮助 尼科

【问题讨论】:

  • moveItemAtPath 不起作用,因为您无法从应用程序包目录中删除文件。
  • @H2CO3 文档目录不是捆绑包的一部分。
  • @Joe 对,抱歉,我看错了问题,出现的常见问题是无法写入 XXXX.app(包本身)。
  • 这样做的原因是我需要将点击 Open in 按钮后传递的文件放入主 Documents 目录。例如,我收到了一个 pdf 作为电子邮件附件,然后单击 open in.. 按钮,我的应用程序必须将该文件放入 Documents 目录

标签: objective-c ios file for-loop nsdocumentdirectory


【解决方案1】:

您可以使用moveItemAtPath:toPath:error:,如下所示。

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"];

//Initialize fileManager first
NSFileManager *fileManager = [NSFileManager defaultManager];

//You should always check for errors
NSError *error;
NSArray *inboxContents = [fileManager contentsOfDirectoryAtPath:documentinbox error:&error];
//TODO: error handling if inboxContents is nil

for(NSString *source in inboxContents)
{
    //Create the path for the destination by appending the file name
    NSString *dest = [documentsDirectory stringByAppendingPathComponent:
                      [source lastPathComponent]];

    if(![fileManager moveItemAtPath:source
                            toPath:dest
                             error:&error])
    {
        //TODO: Handle error
        NSLog(@"Error: %@", error);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2012-04-07
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多