Search code examples
iosswiftproperty-list

PropertyList Decoder decode returns nil


I encode a array of structs. When encoded the returned data has some bytes, which tells me that something was written to the file. But when I decode it returns nil. I don't get any error while decoding. I dont understand why it returns nil after decode.

var allEndpts = [EndPt]()

struct EndPt : Codable {
    var contactStruct  = ContactStruct()
    var purpose: String = String()
}

struct ContactStruct: Codable {
    var firstName:String? = nil
    var lastName:String? = nil
}

private func saveEndPoints() {

    do {
        delegate.documentDirectoryUrl = try FileManager.default.url(
            for: .documentDirectory, 
            in: .userDomainMask, 
            appropriateFor: nil, 
            create: false
        )

        let localFileUrl:URL =
            delegate.documentDirectoryUrl!
                .appendingPathComponent("EndPoints")

        UserDefaults.standard.set(localFileUrl, forKey: "localEndPtUrl")
        print("localEndPtUrl: \(localFileUrl)")
        do {
            let encoder = PropertyListEncoder()
            let data = try encoder.encode(self.allEndpts)
            try data.write(to: localFileUrl)
        } catch {
            print(error)
        }
    } catch {
        print("error")
    }

    retrieveFromFile()
}

func retrieveFromFile() {

    typealias TempArray = [EndPt]
    var temp: TempArray?

    let localFileUrl =  UserDefaults.standard.url( forKey: "localEndPtUrl")
    print("localEndPtUrl: \(localFileUrl)")

    do {
        let data = try Data(contentsOf: localFileUrl!)
        let temp = try PropertyListDecoder().decode(TempArray.self, from: data)
        print("EndPt Array Dump: ", temp)
    } catch {
        print("read error:", error)
    }
}

Solution

  • The problem is that

    var temp: TempArray?
    

    will always be nil unless you change it. And you never change it. When you say

    let temp = try PropertyListDecoder().decode(TempArray.self, from: data)
    

    that is a different temp.