Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 768
itechnician Avatar asked Dec 19 '13 14:12

itechnician


1 Answers

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.

like image 95
Hussain Shabbir Avatar answered Sep 23 '22 15:09

Hussain Shabbir