Appending item from an ObservedResults to an ObservedRealmObject (or Binding to one)

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

I suspect that you’re attempting to store the same object twice (whether in the same or different realms).

What does the view that contains this one look like?

Does selectedItems need to be persisted, or could you use an in-memory array?

I suspect that you’re attempting to store the same object twice (whether in the same or different realms).

You may be right, I’ve presumed that the append operation behaves in two ways, depending on if the realm object is managed; if the object being append is unmanaged, it is written to the realm and the relationship is created; if the object being appended is managed, it only creates the relationship. (This presumption may well be incorrect.)

The parent view looks like this:

struct LogDetailsView: some View {
  @ObservedRealmObject var log: LogEntry

  var body: some View {
    List {
      ForEach(LogListItem.allCases) {
         ...
         SelectTagView(selectedTags: $log.tags)

In the above, log comes from a parent view that uses ObservedResults(LogEntry.self) to display a list.