gpt4 book ai didi

SwiftData: Illegal attempt to establish a relationship between objects in different contexts(SwiftData:非法尝试在不同上下文中的对象之间建立关系)

转载 作者:bug小助手 更新时间:2023-10-28 10:25:13 27 4
gpt4 key购买 nike



I have 2 pretty models and want to create some dummy preview data for these but I'm running into error:

我有两个漂亮的模型,想为它们创建一些虚拟的预览数据,但我遇到了错误:


Illegal attempt to establish a relationship 'person' between objects in different contexts

非法尝试在不同上下文中的对象之间建立“人”关系


The error happens here:

错误发生在以下位置:


@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. Any idea what I'm doing wrong?

我用的是Xcode15测试版8。你知道我哪里做错了吗?


Here are my models for reference:

以下是我的模型供参考:


Item Model

项目模型


@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
)
}
}

Person Model

人物模型


@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"
)
}
}

更多回答
优秀答案推荐

Ran into something similar on the latest Beta.

在最新的测试版上也遇到了类似的情况。


WWDC videos don't mention this explicitly but looking at their data models it seems like all @Relationship fields need to be either:

WWDC视频没有明确提到这一点,但看看他们的数据模型,似乎所有的@Relationship字段都需要:



  • Optional

  • Provide a default value


For example:

例如:


@Model
final class Trip {
var destination: String?
var end_date: Date?
var name: String?
var start_date: Date?

@Relationship(.cascade)
var bucketListItem: [BucketListItem] = [BucketListItem]() //<--

@Relationship(.cascade)
var livingAccommodation: LivingAccommodation? //<--
}

Try setting:

尝试设置:


var person: Person?

In your Item model.

在您的项目模型中。


更多回答

Thanks, that error message is a bit misleading.

谢谢,这个错误消息有点误导。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com