如何收集包含 属性 中的对象数组的对象数组

How to gather an array of objects that contains an array of objects inside a property

我正在尝试创建一个文件包装器来将内容放入其中。

我有这个代码:

class Documents {
  static func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
  }
}

稍后在代码中

let documentsURL = Documents.getDocumentsDirectory()
    
let fileURL = documentsURL.appendingPathComponent("myFile.tb")
do {
   let mainFileWrapper = try FileWrapper(url: fileURL, options: [])

最后一行错误:

{Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

任何想法

当您说 documentsURL.appendingPathComponent("myFile.tb") 时,您并不是在那个地方创建文件。

您需要确保该文件存在于该位置。您可以检查它是否已经存在,如果不存在,您可以创建它。

let documentsURL = Documents.getDocumentsDirectory()
let fileURL = documentsURL.appendingPathComponent("myFile.tb")
do {
    let fileManager = FileManager.default
    if !fileManager.fileExists(atPath: fileURL.path) {
        fileManager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
    }
    let mainFileWrapper = try FileWrapper(url: fileURL, options: [])
} catch {
    print(error)
}

来自 FileWrapper 文档 -

A representation of a node (a file, directory, or symbolic link) in the file system.

因此文件(甚至 empty/new 文件)、文件夹或符号链接必须出现在您创建 FileWrapper 实例的 url/path 中。