Simple KVO example

WebOrCode picture WebOrCode · Jul 26, 2014 · Viewed 29.3k times · Source

I am trying to do simple KVO example, but I am having problems.

This is my *.m file:

#import "KVO_ViewController.h"

@interface KVO_ViewController ()

@property NSUInteger number;

@end

@implementation KVO_ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self addObserver:self forKeyPath:@"number" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)incNumber:(id)sender
{
    _number++;
    NSLog(@"%d", _number);
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"From KVO");

    if([keyPath isEqualToString:@"number"])
    {
        id oldC = [change objectForKey:NSKeyValueChangeOldKey];
        id newC = [change objectForKey:NSKeyValueChangeNewKey];

        NSLog(@"%@ %@", oldC, newC);
    }
}

@end

Note: I have a button which when clicked it will increment the number property.
I want to be notified when number property is changed.

The code is not working and I can not figure it why.

Answer

codester picture codester · Jul 26, 2014

KVO works with setter and getter and in incNumber you are directly accessing iVar so instead of that use self.number

- (IBAction)incNumber:(id)sender
{
    self.number++;
    NSLog(@"%d", self.number);
}