使用 Objective-C 复制或移动文件的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/491809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to copy or move files with Objective-C?
提问by winsmith
I was wondering, is there a best practice to write an OSX programm that copies or moves a file from one place to another?
我想知道,是否有最佳实践来编写将文件从一个地方复制或移动到另一个地方的 OSX 程序?
- 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?
- 有什么可以调用的 NSSomething 方法吗?
- 我必须使用输入/输出流吗?
- 还是仅依靠将命令传递给查找程序的最佳方法?
Bonus question: How do I get percentages a la "copy 12% complete" with one of these methods?
额外问题:如何使用这些方法之一获得“复制 12% 完成”的百分比?
Thanks for your help!
谢谢你的帮助!
回答by Marc Charbonneau
NSFileManager and NSWorkspace both have methods to move, copy, and delete files. Usually you'd use NSFileManager since its easier to work with:
NSFileManager 和 NSWorkspace 都有移动、复制和删除文件的方法。通常你会使用 NSFileManager 因为它更容易使用:
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 可以轻松地将文件移动到垃圾箱,而 NSFileManager 无法做到这一点。
[[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)
查看文档以获取对这两个类的更完整描述。( NSFileManager, NSWorkspace)
回答by Ed Marty
[[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]
[[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]
Here's the link to the class reference:
这是类参考的链接:
回答by Parag Bafna
You can also use FSCopyObjectAsyncfunction. You can display file copy progress and you can also cancel file copy using FSCopyObjectAsync().
Take a look at this post.
您还可以使用FSCopyObjectAsync函数。您可以显示文件复制进度,也可以使用 FSCopyObjectAsync() 取消文件复制。
看看这个帖子。
FSCopyObjectAsync is Deprecated in OS X v10.8
FSCopyObjectAsync 在 OS X v10.8 中已弃用
copyfile(3)is alternative for FSCopyObjectAsync. Hereis example of copyfile(3) with Progress Callback.
copyfile(3)是 FSCopyObjectAsync 的替代方法。这是带有进度回调的 copyfile(3) 示例。

