Hi! I'm experimenting with SwiftData and looking for a situation where one persistentModelID
might result in more than one registered model object reference delivered from a fetch from a single context
. Here is an example of what I have to experiment:
import Foundation
import SwiftData
@Model class Person {
var name: String
init(name: String) {
self.name = name
}
}
func main() {
let configuration = ModelConfiguration(
isStoredInMemoryOnly: true,
allowsSave: true
)
do {
let container = try ModelContainer(
for: Person.self,
configurations: configuration
)
let context = ModelContext(container)
let person = Person(name: "John Appleseed")
context.insert(person)
let persistentModelID = person.persistentModelID
if let left: Person = context.registeredModel(for: persistentModelID),
let right: Person = context.registeredModel(for: persistentModelID) {
print(left === right) // true
}
let descriptor = FetchDescriptor<Person>(
predicate: #Predicate { person in
person.persistentModelID == persistentModelID
}
)
if let left = try context.fetch(descriptor).last,
let right = try context.fetch(descriptor).last {
print(left === right) // true
}
} catch {
print(error)
}
}
main()
This is a very simple command line app that attempts to fetch "two different" registered models… but both approaches (querying directly for persistentModelID
and wrapping persistentModelID
with FetchDescriptor
) seem to consistently deliver objects equal by reference.
Is there any situation where I could set this code up to deliver two registered models different by reference (but equal by value)? Is this anything I have to think about or manage at an "app" level? Is this behavior documented anywhere? Thanks!