33

I was wondering, is there a best practice to write an OSX programm that copies or moves a file from one place to another?

  • is there some NSSomething method I can call?
  • Do I have to work with Input/Output streams?
  • Or is the best way maybe to just rely on passing commands to the finder?

Bonus question: How do I get percentages a la "copy 12% complete" with one of these methods?

Thanks for your help!

winsmith
  • 20,791
  • 9
  • 39
  • 49

3 Answers3

58

NSFileManager and NSWorkspace both have methods to move, copy, and delete files. Usually you'd use NSFileManager since its easier to work with:

if ( [[NSFileManager defaultManager] isReadableFileAtPath:source] )
    [[NSFileManager defaultManager] copyItemAtURL:source toURL:destination error:nil];

However, NSWorkspace can easily move files to the Trash, which NSFileManager can't do.

[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:foldername destination:@"" files:filenamesArray tag:&tag];

Check the documentation for a more complete description of the two classes. (NSFileManager, NSWorkspace)

Sebastian Hojas
  • 4,158
  • 2
  • 27
  • 38
Marc Charbonneau
  • 40,399
  • 3
  • 75
  • 82
15

[[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]

Here's the link to the class reference:

http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/copyItemAtPath:toPath:error:

mattsven
  • 22,305
  • 11
  • 68
  • 104
Ed Marty
  • 39,590
  • 19
  • 103
  • 156
  • 1
    Since the error parameter takes `(NSError **)` type, it may be better to suggest `[[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]` with the & sign. – Makzan Nov 13 '13 at 01:46
5

You can also use FSCopyObjectAsync function. You can display file copy progress and you can also cancel file copy using FSCopyObjectAsync().
Take a look at this post.

FSCopyObjectAsync is Deprecated in OS X v10.8

copyfile(3) is alternative for FSCopyObjectAsync. Here is example of copyfile(3) with Progress Callback.

Community
  • 1
  • 1
Parag Bafna
  • 22,812
  • 8
  • 71
  • 144