Core Data and UserDefaults are both used to storing data on iOS. But there are also many important differences between them. This post leads you to learn important differences between them and figure out when you should use Core Data or UserDefaults.
UserDefaults is an interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app. Moreover, you should store preferences and app settings only into UserDefaults. In another word, you should not be storing critical data and or user data into them.
Core Data is a full-fledged persistent framework that supports large data transactions. Core Data allows you to build a relational entity–attribute model for storing user data.
For example, app preferences like show notifications, toggle switch settings, UISegmentedControl settings all go into UserDefaults. Whereas any data you might fetch using a web service like a list of all cities in a country, a list of todos for a user goes into Core Data.
Pros of UserDefaults
- Easy to store and retrieve data.
- Useful for storing default values with minimum fuzz.
Cons of UserDefaults
- Not suitable for large data sets.
- The performance hit when you try to store and load a large amount of data All or nothing approach.
Pros of Core Data
- Reliable framework to interact and query against data.
- Can be extremely fast when set up correctly (with relationships).
- Powerful capabilities.
Cons of Core Data
- Takes time to master and learn the core concept.
- Needs proper app architecture design to be efficient.
- You cannot have a learn and implement in a day approach with CoreData.
- As you improve your app, you need to improve your data architecture as well.
- Migrating to new versions can be a pain if you are not careful.
In summary, you should use UserDefaults to store the user’s preferences only instead of critical data and user data. In contrast, Core Data is a real database which persists or cache data on a single device, or sync data to multiple devices with CloudKit. However, a disadvantage of Core Data is the studying curve. But don’t worry, my posts can help you learn Core Data as easily as possible:
- How to Create an iOS Project with Core Data Support in Xcode
- How to Add Core Data Support to An Existing Project
- 4 Differences Between Core Data and SQLite You Should Know
- How to Create Core Data Fetch Request with @FetchRequest in SwiftUI
In addition, for UserDefaults study, you can read:
Hope it helps!