How to store Model Class data in User Defaults in Swift?


Saving and Retrieving Custom Object TO User Defaults:

Encoding and Decoding :

The Codable type is a type alias for the Encodable and Decodable protocols. This means that any type conforming to Codable can be encoded and decoded.

Declare a struct Book as follows:-

Now let's see how we can use the above methods to save and retrieve objects.

Setting a Custom Object To User Defaults:

To store a Note object in the defaults database, we need to encode it. This simply means that the Note object is converted to a Data object.

Reading/Getting a Custom Object From User Defaults:

Retrieving the custom object from the defaults database isn't difficult either. We ask the shared defaults object for the Data object and decode it. In other words, we convert the Data object to a Note object.

Before Apple introduced the Codable protocol, the way to convert custom object into NSData is using NSKeyedArchiver with NSCoding protocol like this.

Here you will need to archive the custom object into NSData then save it to user defaults and retrieve it from user defaults and unarchive it again. You can archive it like this.

Thanks for reading!!

Post a Comment