Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode error saying "cannot find type 'TestModelCoreData' in scope when using core data fetch request, yet it compiles and runs

The code below is my view that I am messing around with core data in but it keeps giving me the error that it cannot find the entity in the scope, yet the application runs fine and everything gets saved and fetched just fine.

Here are screenshots of the errors it gives

import SwiftUI

struct ContentView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(
        entity: TestModelCoreData.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \TestModelCoreData.name, ascending: false)
        ]
    ) var entities: FetchedResults<TestModelCoreData>
    
    var body: some View {
        VStack {
            Text("Hello, world!").padding()
            
            Button(action: {
                let newEntry = TestModelCoreData(context: self.moc)
                newEntry.name = "New name"
                
                if self.moc.hasChanges {
                    try? self.moc.save()
                }
            }) {
                Text("Add entry")
            }
            
            List(entities, id: \.self) { entity in
                Text(entity.name ?? "Unknown")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
like image 351
FUNKYJASPER2 Avatar asked Jul 14 '20 05:07

FUNKYJASPER2


3 Answers

I just reopened Xcode 🙄.

SwiftUI 2.0 CoreData issues with new project - 'Cannot find type 'Item' in scope'

like image 134
europeec Avatar answered Nov 10 '22 00:11

europeec


This issue persists as of Xcode 12.2. It is not unique to CoreData. It can be triggered by e.g. creating an extension, then moving that extension to a separate file. If your code builds and runs despite a Swift compiler error "Cannot find 'xyz' in scope", try just closing and reopening your project before clearing caches, deleting derived data, etc.

like image 36
CALL-151 Avatar answered Nov 10 '22 02:11

CALL-151


If none of the solutions provided seems to work ( restarting Xcode, recreating the project, checking if has been added to Target Membership, deleting Derived Data, etc, ... ) and despite the IDE warnings try to build the project anyway with cmd + B . This resolved the issue on my end.

like image 2
gma992 Avatar answered Nov 10 '22 02:11

gma992