Search code examples
cocoafilemovensfilemanager

replaceItemAtURL won't work if I tried to replace item to a different volume


In my cocoa app I have a feature to move file to certain destination. Let's say user has a file /Users/Josh/Desktop/my.zip. User can move this my.zip file to another destination, and my.zip will be gone in Desktop.

In my code I used replaceItemAtURL, because the destination folder may also contain another my.zip:

bMoveSuccess = [[NSFileManager defaultManager] replaceItemAtURL:destinationURL withItemAtURL:sourceURL backupItemName:nil options:0 resultingItemURL:&destinationURL error:&error];

If I call this to move file within the same volume, it works, however if I call this and set the destination to a different volume (ie. a USB key), then I'll got the error msg saying:

Error Domain=NSCocoaErrorDomain Code=512 "The file “my.zip” couldn’t be saved."
UserInfo=0x101b51840 {NSFileOriginalItemLocationKey=file://localhost/Volumes/USB/my.zip,
NSURL=file://localhost/Volumes/USB/my.zip, 
NSFileNewItemLocationKey=file://localhost/Users/Josh/Desktop/my.zip,
NSUnderlyingError=0x101b2e3d0 "The operation couldn’t be completed. Cross-device link"}

Solution

  • This will not work. These methods rely on the newer NSURL bookmark functionality, which can track a file's location even as it's moved while open within the same volume. It will not work for cross-volume moves. You'll have to change your approach (add some additional code to check for this error and handle the case specifically).