Sunday, January 28, 2024
HomeiOS Developmentios - Configure relationships with SwiftData in Preview

ios – Configure relationships with SwiftData in Preview


We’re creating an iOS app utilizing SwiftData. We’ve got Bucket and BucketItem fashions the place a Bucket can have many BucketItem, so there’s a relationship between Bucket and BucketItem. Beneath is a simplified model of the fashions.

import Basis
import SwiftData

@Mannequin
class Bucket {
  var identify: String
  var shared: Bool
  
  @Relationship(deleteRule: .cascade, inverse: BucketItem.bucket) var gadgets = [BucketItem]()
  
  init(identify: String, shared: Bool) {
    self.identify = identify
    self.shared = shared
  }
}

import Basis
import SwiftData

@Mannequin
class BucketItem {
  var content material: String
  var bucket: Bucket
  
  init(content material: String, bucket: Bucket) {
    self.content material = content material
    self.bucket = bucket
  }
}

We present a listing of Bucket with a rely of what number of BucketItem it has. That is working within the app on the gadget and simulator, nevertheless the connection shouldn’t be engaged on the Preview. Beneath is a simplified model of this element with the Preview configuration

import SwiftUI
import SwiftData

struct BucketsData: View {
 var bucket: Bucket //that is offered by a guardian element that makes use of @Question to fetch the Buckets
  
  var physique: some View {
    Record {
      Part(bucket.identify) {
        Textual content("Gadgets: (bucket.gadgets.rely)")
      }
      
    }
  }
}

#Preview {
  let config = ModelConfiguration(isStoredInMemoryOnly: true)
  let container = strive! ModelContainer(for: Bucket.self, configurations: config)
  
  let testBucket = Bucket(identify: "Take a look at Bucket", shared: true)
  container.mainContext.insert(testBucket)
  
  let testItem = BucketItem(content material: "Take a look at Merchandise", bucket: testBucket)
  container.mainContext.insert(testItem)
  
  return BucketsData(bucket: testBucket)
    .modelContainer(container)
}

The listing present the “Take a look at Bucket” with a rely of 0 gadgets. It seems that for some motive the gadgets array shouldn’t be getting populated with the associated BucketItem. How can we repair this?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments