英文:
'RLMException', reason: 'Can't set object of type 'Person' to property of type 'Person'
问题
我有一个Job模型,其中包含以下字段:
`@Persisted var assigned: Person?`
Person模型:
```swift
class Person: Object, Identifiable {
var id: ObjectId { _id }
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String = ""
convenience init(name: String) {
self.init()
self.name = name
}
}
我有一个SwiftUI选择器,允许选择一个人,然后将其保存到Job模型。这在创建时运行良好,但在更新时我收到以下错误:
Terminating app due to uncaught exception 'RLMException', reason: 'Can't set object of type 'Person' to property of type 'Person'
这似乎毫无道理,因为错误本身表明数据类型是相同的。我已经将它们都打印出来,它们是相同的。这里发生了什么?
我尝试过显式转换为Person。我确信我只需将字段设置为新的Person记录即可。
<details>
<summary>英文:</summary>
I have a Job model with the following field:
`@Persisted var assigned: Person?`
Person Model:
class Person: Object, Identifiable {
var id: ObjectId { _id }
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String = ""
convenience init(name: String) {
self.init()
self.name = name
}
}
I have a SwiftUI picker to allow a person to be selected, then it's saved to the Job model. This works fine on create, but on update I get the following error:
`Terminating app due to uncaught exception 'RLMException', reason: 'Can't set object of type 'Person' to property of type 'Person'`
Which doesn't seem to make sense as the error itself states the DataTypes are the same. I have printed them both out and they're identical. What is going on here?
I have tried explicitly casting to person. I'm sure I should just be able to set the field to a new person record.
</details>
# 答案1
**得分**: 1
我搞定了。我从我用来填充Picker的@ObservedResults中获取了所选的Person对象:
```swift
@ObservedResults(Person.self) private var people
我将其更改为从现有的Jobs对象获取realm,然后使用该realm实例运行查询以获取Person记录。然后,将此结果添加到Jobs对象中,没有错误。
英文:
I got it to work. I was getting the chosen Person object from the @ObservedResults I used to populate the Picker:
@ObservedResults(Person.self) private var people
I swapped that to getting the realm from the existing Jobs Object and then running a query using that realm instance to get the Person record. This result was then added to the Jobs object with no error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论