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

17,476

Solution 1

I just reopened Xcode 🙄.

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

Solution 2

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.

Solution 3

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.

Share:
17,476
FUNKYJASPER2
Author by

FUNKYJASPER2

Updated on June 13, 2022

Comments

  • FUNKYJASPER2
    FUNKYJASPER2 almost 2 years

    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()
        }
    }
    
  • Jeremy Field
    Jeremy Field over 2 years
    omg so upsetting
  • Arindam
    Arindam over 2 years
    This solved my error