Leave a rating/review
Notes: 20. Challenge: Saving Property Lists
This course was originally recorded in April 2020. It has been reviewed and all content and materials updated as of November 2021.
Add a new method to your task store that also saves your data, but instead of using JSON use Property Lists. One hint that I can give you is that you have available a PList equivalent of JSONEncoder.
The first thing I did was create a property to store the URL for the PList file where the data will be stored.
let tasksPListURL = URL(fileURLWithPath: "PrioritizedTasks",
relativeTo: FileManager.documentsDirectoryURL).appendingPathExtension("plist")
It’s identical to the JSON file URL except for the property name and the extension of the file. It now uses plist as opposed to json. Then, I added a new method to save the data to a Plist.
private func savePListPrioritizedTasks() {
...
}
In it, I copied the entire do-catch statement and just changed the URL to save to.
do {
let tasksData = try encoder.encode(prioritizedTasks)
try tasksData.write(to: tasksPListURL, options: .atomicWrite)
} catch let error {
print(error)
}
All that remains is to use the right encoder, which is PropertyListEncoder.
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
The output format, as opposed to being pretty printed, is set to XML. You can use OpenStep or Binary as alternative formats, but while the latter will result in smaller file sizes, you won’t be able to easily use them across different platforms or applications if it’s something other than XML.
Notice how you don’t have to touch anything in your model files. That’s because Codable works with different Encoders and Decoders. In this case PropertyListEncoder will take care of things for you, so you don’t have to make tweaks to your model every time you use a different encoding format.
The last thing you want to do is to update didSet for the prioritizedTasks array to save using Property Lists and not JSON.
savePListPrioritizedTasks()
Run your app in the simulator, add, delete, or modify a task, and look at the Document directory of your simulator to view the resulting file.
Fantastic, you are now able to save your array to a .plist file