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

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

问题描述

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

我想覆盖已存在的文件。此方法的默认行为是引发异常/错误File Exists。当文件存在时。没有选择指定它应该覆盖。



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

我会先检查文件是否存在,然后删除它,然后尝试复制?这有一个危险,就是应用程序或设备在文件被删除后的纳秒内关闭,但是新文件没有被复制到那个地方。那么没有什么。

也许我必须先更改新文件的名称,然后删除旧的,然后重新更改新的名称?同样的问题。如果在这个纳秒级别的应用程序或设备关闭和重命名不会发生?

解决方案

你会想做一个在这种情况下,最好通过使用 NSData NSString 来实现原子保存

  NSData * myData = ...; //从某处获取
[myData writeToFile:targetPath atomically:YES];

或者对于 NSString

  NSString * myString = ...; 
NSError * err = nil;
[myString writeToFile:targetPath atomically:YES encoding:NSUTF8StringEncoding error:& err];
if(err!= nil){
//我们有一个错误。
}


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?

解决方案

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];

Or for an 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天全站免登陆