0

I am trying to get notifications for when a property called "currentTopViewPosition" changes. I used the following code to register for the changes and receive them:

[self addObserver:self 
forKeyPath:@"currentTopViewPosition" 
options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld|NSKeyValueObservingOptionPrior 
context:NULL];

Then the receiving side:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"Key Path: %@\n change: %@",keyPath, change);
}

But nothing was getting logged for it.

I tested to make sure the value was actually changing by using an NSTimer to print out its value every 5ms and it was changing.

I've never seemed to get Key-value observing to work, so am I doing something wrong? missing a step?

Thanks!

Micaiah Wallace
  • 1,101
  • 10
  • 17
  • UIKit is not guaranteed to be KVO compliant – danielbeard Apr 21 '15 at 22:24
  • @danielbeard But what does that encompass? This is a custom property in a uiviewcontroller subclass, does that disqualify it? – Micaiah Wallace Apr 21 '15 at 22:26
  • How is it calculated? Can you show where the `currentTopViewPosition` is defined? – danielbeard Apr 21 '15 at 22:27
  • @danielbeard its defined like this: `@property (nonatomic, assign, readonly) ECSlidingViewControllerTopViewPosition currentTopViewPosition;` And it's either a 1 or a 0 (defined by constants) – Micaiah Wallace Apr 21 '15 at 22:39
  • Within that class, do you redeclare the property as `readwrite` or are you using the ivar directly? – danielbeard Apr 21 '15 at 22:43
  • It appears to be getting set directly like so: `_currentTopViewPosition = ECSlidingViewControllerTopViewPositionCentered;` and I didn't find any redeclaring the property. (This is a 3rd party class on github so I don't know it fully in and out) – Micaiah Wallace Apr 21 '15 at 22:46

1 Answers1

0

The easiest way to make your property is to redeclare the property as readwrite inside your implementation file.

@property (nonatomic, readwrite, assign) ECSlidingViewControllerTopViewPosition currentTopViewPosition;

Then when setting the value, make sure you use the property setter. E.g. self.currentTopViewPosition = 1

If you are manually setting the value using an ivar directly, you will have to generate the KVO calls manually. Like this:

[self willChangeValueForKey:@"currentTopViewPosition"];
_currentTopViewPosition = 1;
[self didChangeValueForKey:@"currentTopViewPosition"];
danielbeard
  • 9,120
  • 3
  • 44
  • 58