Fixing Project 10: Codable
Fixing Project 10: Codable êŽë š
NSCoding
is a great way to read and write data when using UserDefaults
, and is the most common option when you must write Swift code that lives alongside Objective-C code.
However, if youâre only writing Swift, the Codable
protocol is much easier. We already used it to load petition JSON back in project 7, but now weâll be loading and saving JSON.
There are three primary differences between the two solutions:
- The
Codable
system works on both classes and structs. We madePerson
a class becauseNSCoding
only works with classes, but if you didnât care about Objective-C compatibility you could make it a struct and useCodable
instead. - When we implemented
NSCoding
in the previous chapter we had to writeencode()
andinit()
calls ourself. WithCodable
this isnât needed unless you need more precise control - it does the work for you. - When you encode data using
Codable
you can save to the same format thatNSCoding
uses if you want, but a much more pleasant option is JSON âCodable
reads and writes JSON natively.
All three of those combined means that you can define a struct to hold data, and have Swift create instances of that struct directly from JSON with no extra work from you.
Anyway, to demonstrate more of Codable
in action Iâd like you to close project12a and open project12b â this should be identical to project 10, because it doesnât contain any of the NSCoding
changes.
First, letâs modify the Person
class so that it conforms to Codable
:
class Person: NSObject, Codable {
âŠand thatâs it. Yes, just adding Codable
to the class definition is enough to tell Swift we want to read and write this thing. So, now we can go back to ViewController.swift
and add code to load and save the people
array.
As with NSCoding
weâre going to create a single save()
method we can use anywhere that's needed. This time itâs going to use the JSONEncoder
class to convert our people
array into a Data
object, which can then be saved to UserDefaults
. This conversion might fail, so weâre going to use if let
and try?
so that we save data only when the JSON conversion was successful.
Add this method to ViewController.swift
now:
func save() {
let jsonEncoder = JSONEncoder()
if let savedData = try? jsonEncoder.encode(people) {
let defaults = UserDefaults.standard
defaults.set(savedData, forKey: "people")
} else {
print("Failed to save people.")
}
}
Just like with the NSCoding
example you need to modify our collection view's didSelectItemAt
method so that you call self?.save()
just after calling self.collectionView.reloadData()
. Again, remember that adding self
is required because we're inside a closure. You then need to modify the image picker's didFinishPickingMediaWithInfo
method so that it calls save()
just before the end of the method.
Finally, we need to load the array back from disk when the app runs, so add this code to viewDidLoad()
:
let defaults = UserDefaults.standard
if let savedPeople = defaults.object(forKey: "people") as? Data {
let jsonDecoder = JSONDecoder()
do {
people = try jsonDecoder.decode([Person].self, from: savedPeople)
} catch {
print("Failed to load people")
}
}
This code is effectively the save()
method in reverse: we use the object(forKey:)
method to pull out an optional Data
, using if let
and as?
to unwrap it. We then give that to an instance of JSONDecoder
to convert it back to an object graph â i.e., our array of Person
objects.
Once again, note the interesting syntax for decode()
method: its first parameter is [Person].self
, which is Swiftâs way of saying âattempt to create an array of Person
objects.â This is why we donât need a typecast when assigning to people
â that method will automatically return [People]
, or if the conversion fails then the catch
block will be executed instead.