我有两个漂亮的模型,想为它们创建一些虚拟的预览数据,但我遇到了错误:
Illegal attempt to establish a relationship 'person' between objects in different contexts个
错误发生在以下位置:
@MainActor
let previewContainer: ModelContainer = {
do {
let container = try ModelContainer(
for: Person.self, Item.self,
configurations: ModelConfiguration(isStoredInMemoryOnly: true)
)
let person = Person.dummy()
container.mainContext.insert(person)
for i in 0 ..< 12 {
let item = Item.dummy(i, person: person) //ERROR!
container.mainContext.insert(item)
}
return container
} catch {
fatalError("Failed to create container \(error)")
}
}()
I'm using Xcode 15 beta 8.你知道我做错了什么吗?
以下是我的模型以供参考:
项目模型
@Model
final class Item {
var note: String
var person: Person
init(note: String, person: Person) {
self.note = note
self.person = person
}
static func dummy(_ index: Int, person: Person) -> Item {
return Item(
note: "Item number \(index)",
person: person
)
}
}
人物模型
@Model
final class Person {
var name: String
@Relationship(
deleteRule: .cascade,
inverse: \Item.person
)
var items: [Item] = []
init(name: String, items: [Item] = []) {
self.name = name
self.items = [Item]
}
static func dummy() -> Person {
return Person(
name: "John Doe"
)
}
}