NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SwiftUI - Problem with MVVM Core Data implementation

Forums > SwiftUI

I have run into an issue regarding Core Data. I am trying to follow the MVVM pattern here. I have broken down into a very simple example code and I'd like to find what's the problem here.

ViewModel

import Foundation
import SwiftUI

class MyListViewModel: ObservableObject {

    @FetchRequest(entity: TestEntity.entity(), sortDescriptors: []) var entriesCoreData: FetchedResults<TestEntity>

    var entries = [MyViewModel]()

    init() {
        fetchEntries()
    }

    func fetchEntries() {
        entries = entriesCoreData.map { MyViewModel.init(entry: $0) }
    }
}

class MyViewModel {

    var name: String
    var date: Date

    init(entry: TestEntity) {
        name = entry.name ?? "Not working"
        date = entry.date ?? Date()
    }
}

Content View

import SwiftUI

struct ContentView: View {

    var myVM = MyListViewModel()

    var body: some View {
        Text("Hello, World!")
    }
}

Core Data Model: Only has one Entity called "TestEntity" with two attributes, name and date.

It seems like calling "fetchEntries" is not allowed. What's my mistake here?

   

What is the error you get?

   

@pd95  

Hi Julian

I confirm, that it is not working if you use the @FetchRequest property wrapper in your model class. If you look at the documentation of the property wrapper you can read:

/// Property wrapper to help Core Data clients drive views from the results of
/// a fetch request. The managed object context used by the fetch request and
/// its results is provided by @Environment(\.managedObjectContext).

As the wrapper takes the managed object context from the environment, the property wrapper is only available in the SwiftUI views. (At least to my knowledge, there is no other place where those environment objects exist/work). You will probably have to get back to NSFetchRequest to do the same thing in your model. Something like the following: (Be aware: I'm not yet an expert ;-))

class MyListViewModel: ObservableObject {

    @Published var entries = [MyViewModel]()

    init() {
        fetchEntries()
    }

    func fetchEntries() {
        // get managed object context from AppDelegate
        let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let request : NSFetchRequest<TestEntity> = TestEntity.fetchRequest()
        do {
            let entriesCoreData = try moc.fetch(request)
            entries = entriesCoreData.map {
                MyViewModel.init(entry: $0)
            }
        } catch {
            print("Fetch failed: Error \(error.localizedDescription)")
            entries = []
        }
    }
}

   

Have a look at this:

https://augmentedcode.io/2020/01/19/using-coredata-with-swiftui/amp/

I Have tested the code and can confirm it works. The solution is to make teh ViewModel an inner class of the main View, that way it has access to the property wrapper e.g:

extension HomeView {
final class ViewModel: NSObject, 
                       NSFetchedResultsControllerDelegate,
                       ObservableObject {

                       /// Code

} // ViewModel
} // HomeView

   

I was having the same issue and this really helped! Thank you!

One question, I don't understand why you need to create a your own model class isn't what Core Data is for?

   

I only use the "ViewModel" class as a convenient place to aggregate the different NSFetchedResultsController<T>s that are used to fetch the initial CoreData, so the class is not really a ViewModel and I will probably rename it.

   

Hello paul, i like your teaching very much and am one of your students. regarding this topic:

  1. will the data fetching code be resided in Model class? such as in your case, the core data CRUD operation. Will model hold this data logic?
  2. Or Model is just plain data structure? I am very confused in this regard. Please let me know if you make time. Thanks.

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!

Save your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.