How to overwrite a file with NSFileManager when copying? How to overwrite a file with NSFileManager when copying? ios ios

How to overwrite a file with NSFileManager when copying?


If you can't/don't want to keep the file contents in memory but want an atomic rewrite as noted in the other suggestions, you can first copy the original file to a temp directory to a unique path (Apple's documentation suggests using a temporary directory), then use NSFileManager's

-replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:

According to the reference documentation, this method 'replaces the contents of the item at the specified URL in a manner that insures no data loss occurs.' (from reference documentation). The copying of the original to the temporary directory is needed because this method moves the original file.Here's the NSFileManager reference documentation about -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:


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


If you're not sure if the file exists, this works on swift 3+

try? FileManager.default.removeItem(at: item_destination)try FileManager.default.copyItem(at: item, to: item_destination)

The first line fails and is ignored if the file doesn't already exist. If there's a exception durning the second line, it throws as it should.