将 NSData 写入文件的最简单方法
NSData *data;
data = [self fillInSomeStrangeBytes];
我现在的问题是如何以最简单的方式将此数据写入文件。
(我已经有一个 NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes
)
NSData *data;
data = [self fillInSomeStrangeBytes];
My question is now how I can write this data
on the easiest way to an file.
(I've already an NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
NSData
有一个名为writeToURL:atomically:
的方法,它完全可以完成您想要做的事情。 查看 文档 < code>NSData 查看如何使用它。NSData
has a method calledwriteToURL:atomically:
that does exactly what you want to do. Look in the documentation forNSData
to see how to use it.请注意,将 NSData 写入文件是一个 IO 操作,可能会阻塞主线程。 特别是当数据对象很大时。
因此建议在后台线程上执行此操作,最简单的方法是使用 GCD,如下所示:
Notice that writing
NSData
into a file is an IO operation that may block the main thread. Especially if the data object is large.Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:
writeToURL:atomically: 或 writeToFile:atomically: 如果您有文件名而不是 URL。
writeToURL:atomically: or writeToFile:atomically: if you have a filename instead of a URL.
您还有
writeToFile:options:error:
或
writeToURL:options: error:
如果NSData
因任何原因保存失败,它可以报告错误代码。 例如:You also have
writeToFile:options:error:
orwriteToURL:options:error:
which can report error codes in case the saving of theNSData
failed for any reason. For example:如果您想手动执行几次而不是编码,最简单的方法是仅使用鼠标:
将鼠标悬停在 NSData 变量上,单击“Eye”按钮,然后导出。
之后选择存储详细信息(文件的名称/扩展名/位置)。
The easiest way, if you want to do this a few times manually instead of coding, is to only use your mouse:
Hold your mouse over your NSData variable, click on the Eye button, and then export.
After that chose the storage details (name/extension/location of the file).