Domanda

Using the line below,

[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];

We can copy a folder but if the folder already exists it throws an exception "File Exists". In order to overwrite a single file, we can achieve it through the following lines:

NSData *myData = [NSData dataWithContentsOfURL:FileURL]; /fetch single file
[myData writeToFile:targetPath atomically:YES];

But I want to copy an already existing folder i.e, overwrite.

Edit : Simple Possibility , I can remove the items before copying them.

Please suggest any more possibilities.

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Remove the item first, with:

[fileManager removeItemAtPath:targetPath error:NULL];

(i.e. ignoring any error)

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top