将struct作为数据保存到文件并再次保存

时间:2017-07-11 16:44:45

标签: swift file io

我正在尝试将由变量和UI对象组成的一些复杂结构的内容写入文件。写入文件似乎工作正常,但一旦我尝试读取和解码,我的程序崩溃。我写的文件似乎也总是16字节,所以可能不是所有的数据都被写入,只是元数据或其他东西?我也在文件的末尾添加“.fire”作为我自己的扩展名,但我不认为这会产生任何影响。请让我知道如何解决这个问题。

struct savable {
    var cs = [String:ScriptObject]() // Complex struct 1
    var sc = [FireObject]() // Complex struct 2
}

func saveData() {

    var s = savable()
    s.cs = currentScripts
    s.sc = structuredContent
    let data = archive(w: s)

    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fireScripts[localScriptIndex] + ".fire")

    do {
        try data.write(to: fileURL, options: .atomic)
    } catch {
        print(error)
    }
}

func readData(index: Int, goFrom: UIViewController) {

    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fireScripts[index] + ".fire")

    do {

        let readData = try Data(contentsOf: fileURL)

        let data = unarchive(d: readData)

        // Breaking here
        print(data.sc[0].type)

    } catch {

    }
}

func archive(w: savable) -> Data {
    var fw = w
    return Data(bytes: &fw, count: MemoryLayout<savable>.stride)
}

func unarchive(d: Data) -> savable {
    guard d.count == MemoryLayout<savable>.stride else {
        fatalError("Error!")
    }

    var w: savable?
    d.withUnsafeBytes({(bytes: UnsafePointer<savable>) -> Void in
        w = UnsafePointer<savable>(bytes).pointee
    })
    return w!
}

0 个答案:

没有答案