如何使用可可将文件复制到便携式驱动器根目录?
我尝试过以下操作
[[NSFileManager defaultManager] copyItemAtPath:@"whatever.txt"
toPath:@"/Volumes/MyDrive" error:©Error];
这给了我错误“操作无法完成。文件存在”
如果我尝试将其复制到“/Volumes/MyDrive/testFolder”,则所有内容都会复制到 testFolder 就好。
I've tried the following
[[NSFileManager defaultManager] copyItemAtPath:@"whatever.txt"
toPath:@"/Volumes/MyDrive" error:©Error];
This gives me the error "The operation couldn’t be completed. File exists"
If I try to copy it to "/Volumes/MyDrive/testFolder" everything copies to testFolder just fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,正如 KennyTM 已经告诉您的那样,错误消息告诉您问题的一个可能原因:文件已经存在。目的地必须不存在;您必须删除它或为目标指定不同的名称。
其次,还有另一个可能的问题原因:您只指定了目标文件夹,而不是完整的目标路径。您必须指定完整的目标路径,包括目标文件名。引用文档:
“复制文件时,目标路径必须以文件名结尾 - 不会隐式采用源文件名。”
如果您希望副本具有路径名
/Volumes/MyDrive/whatever.txt
,那么这就是您需要传递的路径名。另外,在尝试查看错误对象之前,不要忘记检查复制是否成功。仅当复制失败时才应查看错误对象。
我想您会发现
testFolder
实际上是一个文件,具体来说,它是Whatever.txt 的副本。First, as KennyTM already told you, the error message is telling you one possible cause of the problem: The file already exists. The destination must not exist; you must either delete it or give a different name for the destination.
Second, there is another possible cause of the problem: You only specified the destination folder, not the complete destination path. You must specify the complete destination path, including the destination filename. Quoth the documentation:
“When a file is being copied, the destination path must end in a filename—there is no implicit adoption of the source filename.”
If you want the copy to have the pathname
/Volumes/MyDrive/whatever.txt
, that's the pathname you need to pass.Also, don't forget to check whether the copy succeeded before you attempt to look at the error object. You should only look at the error object if the copy failed.
I think you'll find that
testFolder
is, in fact, a file—specifically, it's the copy of whatever.txt.错误不是很清楚吗? “操作无法完成。文件存在”。
-copyItemAtPath:...
的文档指出:如果您想覆盖目标文件,则需要调用
-removeItemAtPath:error:
来删除它。Isn't the error very clear? "The operation couldn’t be completed. File exists". The doc of
-copyItemAtPath:…
states that:You need to call
-removeItemAtPath:error:
to remove the destination file if you want to override it.