Last active
January 6, 2024 07:31
-
-
Save mikeabdullah/4740463 to your computer and use it in GitHub Desktop.
Atomic file copying
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| - (BOOL)atomicCopyItemAtURL:(NSURL *)sourceURL | |
| toURL:(NSURL *)destinationURL | |
| error:(NSError **)outError | |
| { | |
| NSFileManager *manager = [NSFileManager defaultManager]; | |
| NSURL *tempDir = [manager URLForDirectory:NSItemReplacementDirectory | |
| inDomain:NSUserDomainMask | |
| appropriateForURL:destinationURL | |
| create:YES | |
| error:outError]; | |
| if (!tempDir) return NO; | |
| NSURL *tempURL = [tempDir URLByAppendingPathComponent:[destinationURL lastPathComponent]]; | |
| BOOL result = [manager copyItemAtURL:sourceURL toURL:tempURL error:outError]; | |
| if (result) | |
| { | |
| NSURL *resultingURL; | |
| result = [manager replaceItemAtURL:destinationURL | |
| withItemAtURL:tempURL | |
| backupItemName:nil | |
| options:NSFileManagerItemReplacementUsingNewMetadataOnly | |
| resultingItemURL:&resultingURL | |
| error:outError]; | |
| if (result) | |
| { | |
| OBASSERT([[resultingURL absoluteString] isEqualToString:[destinationURL absoluteString]]); | |
| } | |
| } | |
| // Clean up | |
| NSError *error; | |
| if (![manager removeItemAtURL:tempDir error:NULL]) | |
| { | |
| NSLog(@"Failed to remove temp directory after atomic media record writing: %@", error); | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment