I have a view with an ObservedResults
that is used to build a List (of “tags”). My objective is to let the user toggle the rows that represent the items they want to associate with a Binding<List<Tag>>
from an ObservedRealmObject
property.
When I attempt to append an item to the bound list, I get an error: 'Object is already managed by another Realm. Use create instead to copy it into this Realm.'
This makes sense, as I believe the ObservedResults
creates its own realm instance, while the ObservedRealmObject
has its own instance.
However, when I create the collection of tags manually via let tags = observedObject.realm.objects(Tag.self)
, I get the same error when attempting to append an object from that collection to the observed object’s list even though they should now share the same realm.
I’m not sure how to proceed at this point; I’d thought using the same realm as the observed object, I could append new objects to the tag collection, and append/remove a tag from the tag collection to the observed object’s list of tags.
What am I missing? Is there a more appropriate approach?
Original code for reference:
@ObservedResults(Tag.self) var tags
@Binding var selectedItems: RealmSwift.List<Tag>
var body: some View {
List {
ForEach(tags) { tag in
SelectableRow(title: tag.name, isSelected: selectedItems.contains(tag)) {
if let index = selectedItems.firstIndex(of: tag) {
$selectedItems.remove(at: index)
} else {
$selectedItems.append(tag)
}
}
...