KeyWindow bound preferences repeated updates warning

Thank you for this great book, Sarah. Most helpful.
I have put the KeyWindow into my MacOS document-based app to customize some menu commands when my document state is appropriate. This works but I keep getting the following warning in the console:
Bound preference KeyWindowValuesPreference tried to update multiple times per frame.
I have found this error in StackOverflow and other fora, but their solutions haven’t worked (this was after I pulled out the source code for KeyWindow so I could edit it).
eg using DispatchQueue.main.async to encompass the preference change code:
.onPreferenceChange(KeyWindowValuesPreference.self, perform: { value in
DispatchQueue.main.async {
windowObserver.values = value
And I tried this in some other places.
I did not get this in your app, so I’m assuming I am doing something wrong with KeyWindow, but I have only put it in the locations you recommended.
Have you experienced this error? Any suggestions on how to fix or debug it please?

@Sarah any suggestions?

Glad you are enjoying the book - thanks for the feedback.

I have not seen this error, but in other cases, I have noticed such messages in the console. Does your code work? if it does, then I would put this down to some Xcode oddity and ignore it.

It may be that some other data changes are causing your view to refresh frequently and so updating the KeyWindow setting.

In macOS Ventura, you won’t have to use this technique as there is a new EnvironmentValue called controlActiveState that you can use instead. I wrote about it on my personal blog: SwiftUI for Mac 2022 :: TrozWare


1 Like

Thanks for your response. The code does work so it’s not a crucial issue. The number of messages has reduced markedly since I re-factored my View code so it’s likely to be my coding as causative.
I look forward to future SwiftUI enhancements. Cheers.

1 Like