Learn Courses My Dashboard

Codable + Core Data + MVVM

I’m searching for a swiftui tutorial or example that utilizes codable + core data in an MVVM pattern? I’ve struggled to find anything that shows the encode aspect of codable using MVVM. Bonus points for incorporation of async-await.

I’ve found many examples of each in isolation, but none showing the complete life cycle. I’m working towards an API-backed application with a lot of data, and need the quick access core data provides. I’m hoping to present persisted data immediately while syncing down changed data in the background.

Thank you!

Hi @Vaughn

JSON Parsing (Codable) and the MVVM architectural pattern are covered under the iOS Foundations SwiftUI course.

CoreData is covered under iOS Databases SwiftUI

In your case, I think that you need to declare your CoreData models as Codable. So typically, these are NSManagedObject subclasses that are extended to conform to Codable protocol.

What I don’t recommend about this approach is that NSManagedObjects (Core Data model objects) depend on NSManagedObjectContext (a space where your model data objects live). So when you parse (or decode) from JSON, you will need to provide a context for the model object to live in. I know this is not a big deal, but this introduces tight coupling between the model layer and the persistence layer of your app.

If you need external sources, you can check on the following:

Introducing MVVM into your SwiftUI project

(Codable NSManagedObjects)
Using Codable with Core Data and NSManagedObject

(NSManagedObjects as BindableObjects for your ViewModel)
Core Data Model SwiftUI