‘RLMException’,reason: ‘无法将类型为’Person’的对象设置为类型为’Person’的属性’

huangapple go评论69阅读模式
英文:

'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 = &quot;&quot;

convenience init(name: String) {
   self.init()
   self.name = name
}

}


I have a SwiftUI picker to allow a person to be selected, then it&#39;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 &#39;RLMException&#39;, reason: &#39;Can&#39;t set object of type &#39;Person&#39; to property of type &#39;Person&#39;`

Which doesn&#39;t seem to make sense as the error itself states the DataTypes are the same. I have printed them both out and they&#39;re identical. What is going on here?


I have tried explicitly casting to person. I&#39;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.

huangapple
  • 本文由 发表于 2023年5月11日 18:59:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定