Tuesday, April 2, 2024
HomeiOS Developmentios - Lazy loading of dependent relationship in SwiftData

ios – Lazy loading of dependent relationship in SwiftData


I’ve an Order mannequin that incorporates Gadgets

@Mannequin
class Order: Decodable {
  @Attribute(.distinctive) var orderId: String
  var gadgets: [Item]
 }

When contained in the record view, I fetch all of the orders, the Gadgets are usually not loaded and exhibits empty

var physique: some View {
    Checklist {
        DynamicQuery(orderDescriptor) { orders in
            ForEach(orders) { order in
        ForEach(order.gadgets) { merchandise in
          if let sandwichName = merchandise.information?.sandwichName {
            Textual content(sandwichName)
          }
        }
      }
    }
    .onReceive(toolbarModel.$selectedDate) { newDate in
        print("Date modified to: (newDate)")
        getOrders(ofDate: newDate) { end in
            change end result {
                case .success:
                    print("Order Fetch profitable for Date (newDate)")
                case .failure(let error):
                    print("Order Fetch failed with (error)")
            }
        }
    }
}

That is how I’m inserting the orders into modelcontext

let orders = strive JSONDecoder().decode([Order].self, from: jsonData)
                                    

  for order in orders {
//  print(order.gadgets) // crashes the app
    modelContext.insert(order)
  }

I attempted defining the relationshipKeyPathsForPrefetching however doesnt work.

non-public var orderDescriptor: FetchDescriptor<Order> {
        var fetchDescriptor = FetchDescriptor(
            predicate: Order.currentOrders(with: toolbarModel.selectedDate),
            sortBy: [SortDescriptor(Order.time)]
        )
//      fetchDescriptor.relationshipKeyPathsForPrefetching = [.items]

        return fetchDescriptor
    }

I do know the connection are lazy load however I assume if I’m referring the gadgets contained in the record, it ought to load? If I reload the app and wait a bit, I might see some gadgets so looks like its loading however not immediately. Something that I’m lacking?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments