Skip to content

Instantly share code, notes, and snippets.

@mikeabdullah
Last active January 6, 2024 07:31
Show Gist options
  • Select an option

  • Save mikeabdullah/4740463 to your computer and use it in GitHub Desktop.

Select an option

Save mikeabdullah/4740463 to your computer and use it in GitHub Desktop.
Atomic file copying
- (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