SwiftUI Preview fail with Core Data: "Error Domain=NSCocoaErrorDomain Code=516"

Hello,

Since I added Core Data to my SwiftUI project, preview canva is no more working, showing an error explaining that the update took more than 5 seconds (the app is working correctly in simulator).
I opened the preview diagnostic report folder, and found a file named SerializationErrors.txt, with the following message:

Error Domain=NSCocoaErrorDomain Code=516 "“SizeModel+CoreDataClass.swift” couldn’t be linked to “Intermediates” because an item with the same name already exists."

I feel like there is a problem of refreshing the class generated for my Core data model. I tried to follow some recommendations found on this website, deleting the Library/Developer/Xcode/UserData/Previews/Simulator Devices/, or also Library/Developer/Xcode/DerivedData, and cleaning/closing Xcode, but none of them had any effect on the problem.
Doing so, I noticed that in the Previews folder, two Simulator Devices were generated (one empty "Simulator Devices", and one filled "Simulator%20Devices"), and regenerated even if I clear them. I don't know if it could be related, but I don't know anymore where to search...
Sorry to hear you are having problems getting previews working. Crash logs for the preview app will show up in ~/Library/Logs/DiagnosticReports/. It can sometimes take a few minutes for it to generate, so give it a bit time and then see if any are there. Hopefully that will give you some helpful hints on what is causing the crash.
Based upon your description of the situation I am guessing that the preview version of the app has some stale app data (perhaps an old version of a CoreData container that doesn't have migration support to the current version?). To start from a fresh slate you can use the terminal app and run xcrun simctl --set previews delete all.

If that still doesn't resolve issue then probably best next step will be to file a feedback with diagnostics.
We will need the diagnostics Xcode Previews generates in order to make sure we understand the error the previews system is encountering.
  1. When you get an error in Xcode Previews, an error banner appears in the canvas

  2. Click the "Diagnostics" button in that banner

  3. In the sheet that appears, click "Generate Report" in the bottom left of the sheet

  4. Attach (or make from the folder) the resulting zip file to the bug (will be named something like previews-diagnostics-0123456789.zip)

Thanks for the help.
I managed to see the line where the app crashed looking at the DiagnoticReport.

The bug seems to be that the preview was using the App class, where the DataStore (singletons holding the core data container/context) was initiated normally, while in preview it is initiated for preview (as in the sample code provided with Persistence singleton):

Code Block @main
struct MyApp: App {
    let appData = AppData.shared
    let datastore = DataStore.shared
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appData)
                .environment(\.managedObjectContext, datastore.container.viewContext)
        }
    }
}


Changing it for that worked:
Code Block @main
struct MyApp: App {
    let appData = AppData.shared
    let datastore = DataStore.preview
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appData)
                .environment(\.managedObjectContext, datastore.container.viewContext)
        }
    }
}


I think I will gave to put a closure , with a check to verify if I'm in preview or not to initiate shared or preview... I don't understand why there no such need in the Xcode sample swiftui-with-core-data project...

I have this problem too - did you ever come up with a proper solution to this? Switching out the declaration in the App class gets Core Data previews working again but swapping this out every time I want to build or preview is even more annoying than just not using previews.

Also interesting to note this only happens when macOS is the preview target - setting the preview target to an iOS/iPadOS device continues to work without issue.

For anyone still having this issue - I used the following code blcok in my App.swift definition to have it work without swapping it around each time:

#if DEBUG
let dataStore = {
  if (ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1") {
    return DataStore.preview
  } else {
    return DataStore.shared
  }
}()
#else
let dataStore = DataStore.shared
#endif

This little code block seems to let me work across all devices without having to swap anything around. I still can't see why this happens - it definitely isn't needed for the default template so I'm guessing there's some recursion going on somewhere in the app where the datastore is getting instantiated a second time; perhaps to do with how I'm setting up either my Commands menu or my Preferences window (as both of these take the viewContext as either a parameter or an environment respectively).

SwiftUI Preview fail with Core Data: "Error Domain=NSCocoaErrorDomain Code=516"
 
 
Q