Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observer for an integer property

I got an an integer property, which value might change during run-time. Therefore, I would like to register this property to an observer in order to receive a notification and call method, if this value has changed. I red already the Apple Documentation but as far as I understand this is just working for NSObjects and not for integers. In my .h I created @property int activePlayer;.

This is what I am doing in my viewDidLoad

[self.activePlayer addObserver:playerChangedObserver
          forKeyPath:@"activePlayer"
             options:(NSKeyValueObservingOptionNew |
                      NSKeyValueObservingOptionOld)
             context:NULL];

Looking forward for some help. Thanks

UPDATE

Maybe you need some additional information. The .h and .m are implementing an UIViewController, in which I am using a flick gesture. If the gesture is weak, the int is 1, if it is a bit stronger it will change to 2. In my project it makes sense to use this variable, so I can't remove it.

I changed the observer registration into:

[self addObserver:self
              forKeyPath:@"activePlayer"
                 options:(NSKeyValueObservingOptionNew |
                          NSKeyValueObservingOptionOld)
                 context:NULL];

The first self is the observed object, from which the property comes from. The key-path is the property and the second self I took, because it also should receive the message, if the key changes. Do I misunderstand something there?

like image 672
kchromik Avatar asked Mar 10 '26 10:03

kchromik


1 Answers

Have you actually tried this code? The introductory example for key-value observing is for an integer property. It states further on that

If the property is a scalar or a C structure, the value is wrapped in an NSValue object (as with key-value coding).

So, you'll need to unpack it before you can do anything with it, but it should work as is.

like image 182
jrturton Avatar answered Mar 13 '26 01:03

jrturton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!