Saving struct as data to file and back again

2019-09-15 19:28发布

问题:

I'm trying to write the contents of some complex structs made up of variables and UI objects to a file. Writing to file seems to work fine, but once I try to read and decode, my program crashes. The file I write also always seems to be 16 bytes, so maybe not all the data is being written, just the metadata or something? I'm also adding ".fire" to the end of the file as my own extension, but I don't think this should have any effect. Please let me know how I can fix this.

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!
}
标签: swift file io