Search code examples
cocoa-touchkey-value-observing

Key-Value Observer not changing on its own property


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!


Solution

  • 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"];