iOS Development notes: Save data to file

iOS Development notes: Save data to file

Save the file

  • First, create an instance of PropertyListEncoder which will encode the items array, and all the ChecklistItems in it, into some sort of binary data format that can be written to a file.
  • Do catch.
  • The encoder you created earlier is used to try to encode the items array.
  • If the data constant was successfully created by the call to encode in the previous line, the you write data to file using the file path returned by a call to dataFilePath().
  • The catch statement indicates the block of code to be executed if an error was thrown by any line of code in the encoding do block.
  • Handle the caught error.

Example code:

func saveChecklistItems() {
    let encoder = PropertyListEncoder()
    do {
        let data = try encoder.encode(items)
        try data.write(to: dataFilePath(), options: Data.WritingOptions.atomic
    } catch {
        print("Error encoding item array: \(error.localizedDescription)")
    }
}

The Codable protocol

Modify the class will conform to the Codable protocol.

Load the file

  • First, you put the results of dataFilePath() in a temporary constant named path.
  • Try to load the contents of Checklists.plist into a new Data object.
  • When the app does find a Checklists.plist file, you'll load the entire array and its contents from the file using a PropertyListDecoder. So, create the decoder instance.
  • Load the saved data back in to items using the decoder's decode method.

Example code:

func loadChecklistItems() {
    let path = dataFilePath()
    if let data = try? Data(contentsof: path) {
        let decoder = PropertyListDecoder()
        do {
            items = try decoder.decode([ChecklistItem].self, from: data)
        } catch {
            print("Error decoding item array: \(error.localizedDescription)")
        }
    }
}

你可能感兴趣的:(iOS Development notes: Save data to file)