TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Yet another preview crash

Forums > SwiftUI

Hi, new to SwiftUI and Swift in general, but this has been such a helpful site so ...

I have a view that fetches an array of NSManagedObject derived objects and displays some info from this object in a List of NavigationLinks. I pass an individual data object to the child view as an environment object. Something like:

struct ParentView: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(sortDescriptors: [SortDescriptor(\.dateCreated)]) var fetchedItems: FetchedResults<Item>

  var body: some View {
    VStack {
      List() {
        ForEach(fetchedItems) { item in
          NavigationLink {
            ChildView(action: .View)
            .environmentObject(item)
           } label: {
                              ...

This all works but I am having trouble in the previews of the child views. The preview looks like:

struct ChildView_Previews: PreviewProvider
{
    static var previews: some View
    {
        ChildView()
            .environmentObject(Item())
            .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

This works just so long as I don't try to dereference anything in the Item object, but I haven't found a way to intialize the object that xcode doesn't complain about.

Is this good practice to pass fetched objects to child views in the first place? And if so, how do I go about making the preview work?

thanks in advance.

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.