Loading and auto-saving the Shopping List
Now that we have the app working the way we want, there is one thing missing: the app doesn't save our Shopping List every time we make changes to our list. Also, we do not want to show the fake items. So let's see how we can persist the Shopping List and save it every time we make changes. For this we will need to:
- Switch to
Item.swift
and first import the coreFoundation
framework as we will be usingUserDefaults
,PropertyListEncoder
, andPropertyListDecoder
class objects to save our items. Add the following line to the top of the file:
import Foundation
- Have the
Item
class implement theCodable
protocol, which will allow our item to be encoded and decoded to be stored inUserDefaults
.UserDefaults
is a quick and easy way to save user settings or data that is application-specific:
class Item: Codable {
- Add a new instance method called
toggleCheck
, which will return a new item with the same name, but with itsisChecked
value toggled. We will use this...