复制时如何用 NSFileManager 覆盖文件? [英] How to overwrite a file with NSFileManager when copying?

查看:42
本文介绍了复制时如何用 NSFileManager 覆盖文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这种方法来复制文件:

I'm using this method to copy a file:

[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];

我想覆盖已经存在的文件.此方法的默认行为是引发异常/错误文件存在".当文件存在时.没有选项可以指定它应该覆盖.

I want to overwrite a file when it exists already. The default behavior of this method is to throw an exception/error "File Exists." when the file exists. There's no option to specify that it should overwrite.

那么最安全的方法是什么?

So what would be the safest way to do this?

我会先检查文件是否存在,然后删除它,然后再尝试复制吗?这可能会导致应用程序或设备在文件被删除后的纳秒内立即关闭,但新文件尚未复制到该位置.然后就什么都没有了.

Would I first check if the file exists, then delete it, and then attempt to copy? This has the danger that the app or device goes OFF right in the nanosecond after the file has been deleted but the new file hasn't been copied to that place. Then there's nothing.

也许我必须先更改新文件的名称,然后删除旧文件,然后重新更改新文件的名称?同样的问题.如果在这纳秒内应用或设备关闭并且没有发生重命名怎么办?

Maybe I would have to change the name of the new file first, then delete the old, and then re-change the name of the new? Same problem. What if in this nanosecond the app or device goes OFF and renaming doesn't happen?

推荐答案

在这种情况下,您希望进行原子保存,最好使用 NSDataNSStringwriteToFile:atomically: 方法(及其变体):

You'd want to do an atomic save in this case, which would be best achieved by using NSData or NSString's writeToFile:atomically: methods (and their variants):

NSData *myData = ...; //fetched from somewhere
[myData writeToFile:targetPath atomically:YES];

或者对于 NSString:

NSString *myString = ...;
NSError *err = nil;
[myString writeToFile:targetPath atomically:YES encoding:NSUTF8StringEncoding error:&err];
if(err != nil) {
  //we have an error.
}

这篇关于复制时如何用 NSFileManager 覆盖文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆