考虑以下两个代码示例:
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/