有没有办法让结构类型数组写入文件?

Is there any way to let struct type array write to file?

我只想写一个struct类型的数组到一个文件中,但是我写完之后,没有创建文件没有任何错误提示!!!???

代码:

struct temp {
    var a : String = ""
    var b : Date = Date()

    init(
        a : String = "",
        b : Date = Date(),
    ) {
        self.a = ""
        self.b = Date()
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var b = [temp]()
    var c = temp()
    c.a = "John"
    c.b = Date()
    b.append(c)
    c.a = "Sally"
    b.append(c)

    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

        let fileURL = dir.appendingPathComponent("testFile")

        do{
            (b as NSArray).write(to: fileURL, atomically: true)
        }catch{
            print(error)
        }
    }

    getTheFile()
}

func getTheFile() {

    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let fileURL = dir.appendingPathComponent("testFile")
        do {
            print(try String(contentsOf: fileURL))
        }catch{
            print("read error:")
            print(error)
        }
    }
}

getTheFile()

中有错误信息

读取错误: Error Domain=NSCocoaErrorDomain Code=260 “无法打开文件“testFile”,因为没有这样的文件。

如果数组的内容都是属性列表对象(如:NSString、NSData、NSArray、NSDictionary),那么只能使用writeToFile方法将数组写入文件。 在您的实现中,数组包含结构,它是一个值类型,而不是一个对象。这就是您收到错误的原因。

您不能将自定义结构写入磁盘。你必须序列化它们。

最简单的方法是 Codable 协议和 PropertyListEncoder/Decoder

struct Temp : Codable { // the init method is redundant
    var a = ""
    var b = Date()
}

var documentsDirectory : URL {
    return  try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var b = [Temp]()
    var c = Temp()
    c.a = "John"
    c.b = Date()
    b.append(c)
    c.a = "Sally"
    b.append(c)

    let fileURL = documentsDirectory.appendingPathComponent("testFile.plist")
    do {
        let data = try PropertyListEncoder().encode(b)
        try data.write(to: fileURL)
        getTheFile()
    } catch {
        print(error)
    }
}

func getTheFile() {
    let fileURL = documentsDirectory.appendingPathComponent("testFile.plist")
    do {
        let data = try Data(contentsOf: fileURL)
        let temp = try PropertyListDecoder().decode([Temp].self, from: data)
        print(temp)
    } catch {
        print("read error:", error)
    }
}

注:

在 Swift 中 从不 使用 NSArray/NSDictionary API 来读取和写入 属性 列表。使用 CodablePropertyListSerialization.