将目录的内容复制到Documents目录

时间:2012-07-25 16:41:35

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

我遇到问题,我需要将Documents子目录的内容移动到Documents Directory的“root”。 为此,我想将子目录的所有内容复制到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循环,每个文档将文档从子目录复制到文档目录。

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

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

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

1 个答案:

答案 0 :(得分:2)

您可以按如下方式使用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);
    }
}
相关问题