【问题标题】:How can I read from and write to files using Swift on a mac?如何在 Mac 上使用 Swift 读取和写入文件?
【发布时间】:2014-08-12 23:45:52
【问题描述】:

我一直在互联网上寻找这个问题的答案,我得到的每个答案要么没有用,要么非常复杂,要么仅适用于 iOS,要么是三者的组合。我只是在寻找一种在 Swift 中执行文件 I/O 以在 Mac 上使用的简单方法。所以我想混合 c++ 和 swift 的方法也可以,但是我遇到了和以前一样的问题。任何帮助将不胜感激!

【问题讨论】:

  • “文件 I/O”是一个大主题。您最好询问一个具体示例,说明您想做什么、尝试过什么以及“没有奏效”是什么意思。

标签: swift macos file-io


【解决方案1】:

Abhi Beckert's 代码更新到 Swift 3:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.appendingPathComponent("foo.txt")

// write to it
try! str.write(to: fileUrl!, atomically: true, encoding: String.Encoding.utf8)

【讨论】:

    【解决方案2】:

    有很多选择,这取决于您要编写的内容以及数据的大小等(数百兆字节的数据需要不同的技术)。

    但最简单的方法是:

    import Cocoa
    
    var str = "Hello, playground"
    
    // get URL to the the documents directory in the sandbox
    let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
    
    // add a filename
    let fileUrl = documentsUrl.URLByAppendingPathComponent("foo.txt")
    
    // write to it
    str.writeToURL(fileUrl, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
    

    可能会引起您注意的一件事是 OS X 具有严格的沙盒功能,以防止您可以写入磁盘的哪些部分。作为用户将随机代码粘贴到 Xcode 中并防止错误擦除某人的整个硬盘驱动器的安全措施...... Playground 强制执行沙箱,尽管许多 Mac 应用程序不使用沙箱(它通常仅对部署在 Apple 商店中的应用程序启用)。

    你的应用在磁盘上有一个沙箱,你可以写入,这就是 NSFileManager() 返回上面的 URL。

    要在沙盒中为磁盘的其余部分打孔,您需要让用户参与进来。例如,如果他们将文件拖到您的应用程序图标上,您可以对其进行写入。如果他们在打开或保存面板中选择一个文件,那么您可以写入该文件。如果用户选择了一个目录,甚至是文件系统的根目录,你可以写入选择的所有后代。

    也可以在应用程序启动时保持对文件/目录的访问,尽管我从未研究过它是如何工作的。如果您将其用于基于文档的应用程序,则 NSDocumentController 会为您执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 2012-09-15
      • 2015-07-26
      • 2011-08-07
      • 2020-02-09
      • 2023-03-22
      • 2015-04-10
      相关资源
      最近更新 更多