Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

swift - Saving struct as data to file and back again

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!
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...