SwiftUI - nil is not a legal NSPersistentStoreCoordinator for searching for entity name

395 Views Asked by At

I get this error when I try to FetchRequest to see if core data has an item or not. I already checked other questions about this error but I couldn't solve it.

The code below crashes the app when I try to find an existing title inside my core data even before adding any item, that's why maybe it sais that nil is not valid. The fact is that I used this method many times in my app and I never got this error but this time I did.

func checkItem(title: String, entityName: String) -> Bool {
        let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entityName)
        request.predicate = NSPredicate(format: "title == %@", title)
        request.fetchLimit = 1
        var trueFalse = true
        do {
            let count = try managedObjectContext.count(for: request)
            if count == 0 {
                trueFalse = false
            } else {
                trueFalse = true
            }
        } catch {
            print(error)
        }
        return trueFalse
   }

And this is how I'm trying to access the information from Core Data

Image(systemName: self.checkItem(title: self.title, entityName: self.entityName) ? "heart.fill" : "heart")

Edit: I'm trying to call it inside a sheet but if I use it in another View I don't get the error anymore. Is there any conflict between accessing Core Data information and sheets?

0

There are 0 best solutions below