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!