How to overwrite a folder using [NSFileManager defaultManager] when copying?

I would like to add one more using delegate, in order to override files with copyItemAtPath (NSFileManager) function use:

[[NSFileManager defaultManager] setDelegate:self];
[[NSFileManager defaultManager] copyItemAtPath:fileOrigin toPath:fileDestin error:&error];

and implement the delegates optional function:

 - (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    if ([error code] == NSFileWriteFileExistsError) //error code for: The operation couldn’t be completed. File exists
        return YES;
    else
        return NO;
}

The default behavior of NSFileManager method is to throw an exception/error "File Exists." when the file exists. But still if you want to overwrite using NSFileManager then it provides one api for that which is mentioned below replaceItemAtURL as well in first solution:-

Also there are three solutions to achieve that

First Solution

[filemanger replaceItemAtURL:url1 
               withItemAtURL:url2
              backupItemName:@"/Users/XYZ/Desktop/test.xml"
                     options:NSFileManagerItemReplacementUsingNewMetadataOnly 
            resultingItemURL:nil error:nil];

Using the above API you can overwrite the file contents. But before that you have to take the backup of your source path in your temporary directory.

Second Solution

Already you have mentioned in your question using NSData writeToUrl.

Third Solution

trojanfoe has mentioned in their answer. i.e. remove the item being overwritten beforehand.


Remove the item first, with:

[fileManager removeItemAtPath:targetPath error:NULL];

(i.e. ignoring any error)