Preview Crashes when using @FetchRequest

I'm trying to load items from the database into a list, it works fine on device and simulator but Preview will always crash with the following message:

" Cannot preview in this file — Connection interrupted: send message to agent"

Here's my code

Code Block SwiftUI
struct SettingsView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: ChildProfile.entity(), sortDescriptors: []) var children: FetchedResults<ChildProfile>
    
    var body: some View {
        VStack {
            List {
                Section(header: Text("Children")) {
                    ForEach(children, id: \.id) { child in
                        ChildRow(child: child)
                    }
                }
            }
        }
    }
}
struct SettingsView_Previews: PreviewProvider {
    static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    
    static var previews: some View {
        let defaultChild = ChildProfile(context: moc)
        defaultChild.id = UUID()
        defaultChild.name = "Lex"
        return SettingsView().environment(\.managedObjectContext, moc)
    }
}


Previewing ChildRow with the same preview code works fine in the canvas

Is this a bug in Xcode or am I missing something?

Howdy,

Sorry to hear you are having problems using Xcode Previews. There is an unfortunate regression in current builds where our more helpful error messages aren't showing up in the UI, and instead you get a more generic one. In this case I think you are likely seeing a crash in your app, and you can verify if that is indeed the case by monitoring/looking for crash logs for the app you are previewing in ~/Library/Logs/DiagnosticReports/. If you find a crash then that should hopefully contain some hints as to what is causing the preview to fail.
Looking at the diagnostics generated by Preview gives me the following message



Error Domain=NSCocoaErrorDomain Code=516 "“ChildProfile+CoreDataClass.swift” couldn’t be linked to “Intermediates” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/Users/james/Library/Developer/Xcode/DerivedData/BedtimeClock-hehxrojiiepyadgitseedusiyozd/Build/Intermediates.noindex/Previews/Bedtime Clock/Intermediates.noindex/Bedtime Clock.build/Debug-iphonesimulator/Bedtime Clock.build/DerivedSources/CoreDataGenerated/Model/ChildProfile+CoreDataClass.swift, NSUserStringVariant=(
Link
), NSDestinationFilePath=/var/folders/dp/hztz
hf572q26jwx6vb9nqpw0000gn/T/previews-diagnostics-20200713-200707/Intermediates/ChildProfile+CoreDataClass.swift, NSFilePath=/Users/james/Library/Developer/Xcode/DerivedData/Bedtime_Clock-hehxrojiiepyadgitseedusiyozd/Build/Intermediates.noindex/Previews/Bedtime Clock/Intermediates.noindex/Bedtime Clock.build/Debug-iphonesimulator/Bedtime Clock.build/DerivedSources/CoreDataGenerated/Model/ChildProfile+CoreDataClass.swift, NSUnderlyingError=0x7fb78a150620 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}

I have no idea what to do with this extra information



I am seeing this same issue in beta 4 released today. I have tried clearing DerivedData and it is still happening
I got this working in a strange roundabout way. Looking through the crash logs, I saw this:
Code Block
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'


My FetchRequest was similar to yours:
Code Block swift
@FetchRequest(entity: Movie.entity(), sortDescriptors: [])
var movies: FetchedResults<Movie>


Moving fetch request creation to a new static variable and using another @FetchRequest wrapper, it now does not crash:

Code Block swift
static var getMoviesFetchRequest: NSFetchRequest<Movie> {
        let request: NSFetchRequest<Movie> = Movie.fetchRequest()
        request.sortDescriptors = []
        return request
   }


Code Block swift
@FetchRequest(fetchRequest: getMoviesFetchRequest)
var movies: FetchedResults<Movie>


And now it works. I am not sure why, but something is going on with the entity not being set. I hope to file a bug report tomorrow with sample code.






I filed the bug report here. I attached a sample project along with the crash reports: FB8276747
I've been having this issue to an I found that changing from this

Code Block
struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
        .environment(\.managedObjectContext, CoreDataManager.shared.context)
    }
}


to this has been the solution for me. No idea why this works, but it does.

Code Block
struct Test_Previews: PreviewProvider {
    static var previews: some View {
        let context = CoreDataManager.shared.context
        return Test()
        .environment(\.managedObjectContext, context)
    }
}


I tried doing the same thing, but it didn't work in my case. I'm not sure why. bknope's solutions works, though!

Preview Crashes when using @FetchRequest
 
 
Q