Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

you should implement in your .m

observeValueForKeyPath:ofObject:change:context:

and you should use

self.activePlayer = 1;

to set your 'activePlayer' property

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top