iphone - 为什么使用 NSFileManager 而不是仅使用 NSData 的 writeToFile :atomically: method when creating a new file?

标签 iphone objective-c ios cocoa-touch nsfilemanager

考虑以下两个代码示例:

    NSData *imgData = UIImagePNGRepresentation(imgFull);
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];   
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"itemImg_%i.png", timestamp]]; //add our image to the path
    [imgData writeToFile:fullPath atomically:YES];

NSData *imgData = UIImagePNGRepresentation(imgFull);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];   
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"itemImg_%i.png", timestamp]]; //add our image to the path
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:fullPath contents:imgData attributes:nil];

第二个示例需要额外的代码行和 NSFileManager 对象的初始化,而第一个示例只是将 NSData 对象imgData 写入文件。第一个示例的另一个优点是它可以覆盖具有相同名称的预先存在的文件。

我的问题是:在创建新文件时,在什么情况下您真正想要使用 NSFileManager 及其方法 createFileAtPath:contents:attributes:

最佳答案

NSFileManager 方法的优点是 attributes 字段:

A dictionary containing the attributes to associate with the new file. You can use these attributes to set the owner and group numbers, file permissions, and modification date. For a list of keys, see “File Attribute Keys.” If you specify nil for attributes, the file is created with a set of default attributes.

此功能在 iOS 上使用不常见,但 NSFileManager 比 iOS 老得多。

顺便说一句,您描述的额外行几乎从未出现在实际代码中。要么你已经有一个你出于其他原因使用的 fileManager 变量,要么你将两行合并为一行:

[[NSFileManager defaultManager] createFileAtPath:fullPath contents:imgData attributes:nil];

还有一个。如您所见:

An additional advantage of the first example is that it can overwrite a pre-existing file that has the same name.

好吧,这是优势还是劣势取决于您想要什么。如果你的意思是“创建这个文件,但如果它已经存在就不要覆盖它”,那么 FM 方法就方便多了。覆盖现有文件可能是错误的;这将节省您对 fileExistsAtPath: 的调用。也许你想创建一个空文件,如果它不存在,但如果它存在,就不要管它。简单:将 [NSData data] 作为 contents 值传递。

所以哪个更好取决于你要解决什么问题。

关于iphone - 为什么使用 NSFileManager 而不是仅使用 NSData 的 writeToFile :atomically: method when creating a new file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9466865/

相关文章:

ios - Swift:executeFetchRequest:无法转换类型为 'Any Object' 的值

ios - iOS 下载应用程序时的通知

objective-c - 当我尝试使用两个 CIFilter 时出现一些问题

javascript - SocketIO 发送带有参数的事件?

ios - 在 CGContext 中绘制透明 PNG 显示为黑色

ios - 如何在 Xcode 中删除空白并将背景扩展到全屏?

ios - 如何在 UIImageView 上实现点击并按住?

iPhone ivar 命名约定

iphone - 切换标签栏时检测选定的标签栏

iOS - 处理多个事件 View