0

I have a SwiftUI project using CoreData Database with a Product entity in it. It has 2 attributes, id, and barcode. Then I create a fetch request that seems to work but will result in an empty [Products].

When the view appears on screen I get the error

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1df9bda98) on the ForEach and no other information.

I tried to make it as simple as possible and I still have the problem. I tried to delete the xcdatamodel file entirely and recreate it and I keep have the problem.

private struct ProductList: View {
@FetchRequest(
    entity: Product.entity(),
    sortDescriptors: []
) var products: FetchedResults<Product>


var body: some View {
    VStack {
        List{
            ForEach(products, id: \.id) { product in
                ProductRow(product: product)
            }
        }
    }

}

}

private struct ProductRow: View {
var product: Product

var body: some View {
    Text(product.barcode ?? "No name given")
}

}

Screencapture of the problematic code

1 Answers1

0

Before using @FetchRequest you must first have injected a Core Data managed object context into the environment, otherwise your products is not empty, but nil

see https://github.com/andrewcbancroft/BlogIdeaList-SwiftUI/tree/master/BlogIdeaList-SwiftUI for further details

user3441734
  • 16,722
  • 2
  • 40
  • 59
  • Thanks for your response. I did add @Environment(\.managedObjectContext) var context to the ProductList: View and I made sure that it is created in the Scene Delegate withn 'guard let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext else { fatalError("Unable to read managed object context.") } let startScreen = StartScreen().environment(\.managedObjectContext, context)'But the exact same problem still exist – Glenn Drescher Feb 20 '20 at 06:59
  • Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) – Glenn Drescher Feb 20 '20 at 07:14