In this post, I
will discuss how to save a custom object in UserDefaults. We will use Codable and JSON to save and retrieve data from UserDefaults
.
Before we begin let me caution you UserDefaults
are not your database. Use CoreData or Realm for all your heavy lifting.
Make your class/Type conform to codable protocol
This is the first step. You need to make your Class and any nested object’s class conform to Codable
protocol. It can be done as shown below
struct Product:Codable{ var title:String? var description:String? var unitPrice:Double? var quantity:Double? var id: Int? }
Saving Custom object to UserDefaults
In order to save the custom object, we need to convert it to data and save that data to UserDefaults
. For this, we will use JSONEncoder
let product = Product() let data = try! JSONEncoder().encode(product) //this is for demo use try properly //Save the data to UserDefaults UserDefaults.standard.set(data, forKey: "PRODUCTS")
Retrieving custom object from UserDefaults
In order to retrieve the custom object from UserDefaults
we will use JSONDecoder
.
let data = UserDefaults.standard.array(forKey: "PRODUCTS") as? Data; if data != nil{ let product = try! JSONDecoder().decode(Product.self, from: data) //use product }
So you have successfully saved and retrieved a custom swift object in UserDefault
good job.