Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c copyItemAtPath始终失败,文件存在错误_Objective C_Cocoa_Nsfilemanager - Fatal编程技术网

Objective c copyItemAtPath始终失败,文件存在错误

Objective c copyItemAtPath始终失败,文件存在错误,objective-c,cocoa,nsfilemanager,Objective C,Cocoa,Nsfilemanager,我正在尝试使用copyItemAtPath复制目录,但每次复制失败时都会出现“操作无法完成。文件存在”错误 这是我正在使用的代码 NSLog(@"Copying from: %@ to: %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"], path); if(![file_manager copyItemAtPath:[NSString stringWithFormat:@"%@", [[NS

我正在尝试使用copyItemAtPath复制目录,但每次复制失败时都会出现“操作无法完成。文件存在”错误

这是我正在使用的代码

NSLog(@"Copying from: %@ to: %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"], path);
if(![file_manager copyItemAtPath:[NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"]] toPath:[NSString stringWithFormat:@"%@", path] error:&error]) {
      NSLog(@"%@" [error localizedDescription]);
}
日志示例-

"Copying from: /Users/testuser/Sites/example_site to: /Users/testuser/Desktop"
"The operation couldn’t be completed. File exists"
你知道我做错了什么吗


提前谢谢

您似乎试图将文件“/Users/testuser/Sites/example\u site”复制到文件“/Users/testuser/Desktop/example\u site”,假设您只需指定目标目录,它将使用源文件名。这是行不通的。引述:

复制文件时,目标路径必须以文件名结尾,因为源文件名没有隐式采用


您正在尝试复制具有相同文件名的内容。试着这样做:

- (BOOL)copyFolderAtPath:(NSString *)sourceFolder toDestinationFolderAtPath:(NSString*)destinationFolder {
    //including root folder.
    //Just remove it if you just want to copy the contents of the source folder.
    destinationFolder = [destinationFolder stringByAppendingPathComponent:[sourceFolder lastPathComponent]];

    NSFileManager * fileManager = [ NSFileManager defaultManager];
    NSError * error = nil;
    //check if destinationFolder exists
    if ([ fileManager fileExistsAtPath:destinationFolder])
    {
        //removing destination, so soucer may be copied
        if (![fileManager removeItemAtPath:destinationFolder error:&error])
        {
            NSLog(@"Could not remove old files. Error:%@",error);
            [error release];
            return NO;
        }
    }
    error = nil;
    //copying destination
    if ( !( [ fileManager copyItemAtPath:sourceFolder toPath:destinationFolder error:&error ]) )
    {
        NSLog(@"Could not copy report at path %@ to path %@. error %@",sourceFolder, destinationFolder, error);
        [error release];
        return NO;
    }
    return YES;
}