Skip to content

Instantly share code, notes, and snippets.

@domkm
Created February 18, 2024 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domkm/cf6c5749eac9053aa0b505efbb05fff7 to your computer and use it in GitHub Desktop.
Save domkm/cf6c5749eac9053aa0b505efbb05fff7 to your computer and use it in GitHub Desktop.
import SwiftData
import SwiftUI
@Model final class Parent {
init() {
child = Child()
}
@Transient let uuid = UUID()
@Relationship(deleteRule: .cascade, inverse: \Child.parent) var child: Child?
}
@Model final class Child {
init(){}
@Transient let uuid = UUID()
var parent: Parent?
}
struct ParentChildView: View {
@Environment(\.modelContext) var modelContext
@Query var parents: [Parent]
var body: some View {
VStack {
Text("Test")
Spacer()
ForEach(parents) { parent in
Text("Parent === itself: \(String(describing: parent === parent))")
Text("Parent.uuid == itself \(String(describing: parent.uuid == parent.uuid))")
Text("Child === itself when retrieved twice: \(String(describing: parent.child === parent.child))")
Text("Child.uuid == itself when retrieved twice: \(String(describing: (parent.child!.uuid == parent.child!.uuid)))")
let child = parent.child
Text("Child.uuid == itself when retained: \(String(describing: (parent.child!.uuid == parent.child!.uuid)))")
}
}
.onAppear {
modelContext.insert(Parent())
try! modelContext.save()
}
}
}
#Preview {
ParentChildView().modelContainer(for: [Parent.self, Child.self], inMemory: true)
}
// Parent === itself: true
// Parent.uuid == itself true
// Child === itself when retrieved twice: true
// Child.uuid == itself when retrieved twice: false
// Child.uuid == itself when retained: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment