A little KVO question

Hi! I’m trying to subscribe to things with KVO, and it seemingly works, but get this message after running the script more than once:

objc.error: Observer is overriding existing Objective-C class

import objc
from Foundation import NSObject, NSKeyValueObservingOptionNew, NSKeyValueChangeNewKey

font = Glyphs.font

class Observer( NSObject ):
    def observeValueForKeyPath_ofObject_change_context_( self, path, object, changeDescription, context ):
        print( '"%s" has changed to "%s"' % (path, changeDescription[NSKeyValueChangeNewKey]))

observer = Observer.new()
font.addObserver_forKeyPath_options_context_( observer, 'familyName',  NSKeyValueObservingOptionNew, 0 )

font.familyName = 'hello'

I assume the class should be removed in the end, but can’t seem to find how to do so? Or is this not a good way to subscribe to stuff altogether? Could you please give a piece of advice?

You can’t rerun a scripts that defines a class that inherits from NSObject. That is a limitation of the objectiveC runtime.
You can try to put the class into a module and just use it to get the KVO notifications and out the stuff you like to do with it in the script file as a python object.

1 Like

Thanks a lot!

May I ask why could it be that observing some font’s properties work and others don’t?
For instance, observing kerning or familyName works fine, but changes in selectedFontMaster or currentText don’t trigger the observer at all.

Properties that are computed in the python wrapper do not trigger KVO. Only the native objC properties will trigger it.
So you can check the wrapper implementation to see if you could find some underlying properties.

What are you trying to do?