Proud Member Proud Member - 1 year ago 80
iOS Question

How to overwrite a file with NSFileManager when copying?

I'm using this method to copy a file:

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

I want to overwrite a file when it exists already. The default behavior of this method is to throw an exception/error "File Exists." when the file exists. There's no option to specify that it should overwrite.

So what would be the safest way to do this?

Would I first check if the file exists, then delete it, and then attempt to copy? This has the danger that the app or device goes OFF right in the nanosecond after the file has been deleted but the new file hasn't been copied to that place. Then there's nothing.

Maybe I would have to change the name of the new file first, then delete the old, and then re-change the name of the new? Same problem. What if in this nanosecond the app or device goes OFF and renaming doesn't happen?

Answer Source

You'd want to do an atomic save in this case, which would be best achieved by using NSData or NSString's writeToFile:atomically: methods (and their variants):

NSData *myData = ...; //fetched from somewhere
[myData writeToFile:targetPath atomically:YES];

Or for an NSString:

NSString *myString = ...;
NSError *err = nil;
[myString writeToFile:targetPath atomically:YES encoding:NSUTF8StringEncoding error:&err];
if(err != nil) {
  //we have an error.