2 / 2
Jun 2024

I have a very simple macOS SwiftUI view (part of a NavigationSplitView) that, when adding an object to @ObservedRealmObject, deselects the selected element in a List. Furthermore, after adding an object and then clicking on an element in the list, it ‘blinks’ and doesn’t select - it almost appears it’s being refreshing right after clicking.

The two Realm objects are taken from the example project in the documentation.

Here’s the code that duplicates the first issue.

struct SidebarView: View { @ObservedRealmObject var itemGroup: ItemGroup @Binding var selectedItem: Item? var body: some View { Text("Sidebar") List(selection: $selectedItem) { let _ = print("refreshing list") ForEach(itemGroup.items) { item in Text(item.itemName) .tag(item) } } Button(action: { let _ = print("adding item") let randomName = "\(randomAdjectives.randomElement()!) \(randomNouns.randomElement()!)" let user = app?.currentUser let item = Item(itemName: randomName, isFavorite: true, ownerId: user!.id) $itemGroup.items.append(item) }, label: { Label("Add Item", systemImage: "plus.circle") }) .padding() } } #Preview { let realm = ItemGroup.previewRealm let itemGroup = realm.objects(ItemGroup.self) return SidebarView(itemGroup: itemGroup.first!, selectedItem: .constant(nil) ) }

and the SidebarView is called from a ContentView here

struct ContentView: View { @ObservedResults(ItemGroup.self) var itemGroups @State private var selectedItem: Item? = nil var body: some View { NavigationSplitView { if let itemGroup = itemGroups.first { let _ = print("showing first item group") SidebarView(itemGroup: itemGroup, selectedItem: $selectedItem)

macOS project: 14.5
Realm SPM : 10.50.1
XCode: 15.4

As additional issue/question, I would really like to select the added object when it’s added but this

$itemGroup.items.append(item) selectedObject = item

doesn’t appear to work or really do anything. Any ideas?

Note that replacing the Text()

Text(item.itemName) .tag(item)

with this

NavigationLink(item.itemName, value: item)

‘fixes’ the issue but then this error now appears in the console

List with selection: SelectionManagerBox<Item> tried to update multiple times per frame.

Any ideas?