1
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property BOOL myBoolean;
@end

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize myBoolean;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
        myBoolean = false;
    [self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionNew context:nil];
    myBoolean = true;

}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if([keyPath isEqual:@"myBoolean"]){
        NSLog(@"changed detected");
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [self removeObserver:self forKeyPath:@"myBoolean"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Here I am trying to do a simple value change checking with KVO. I wasn't sure what to put in the forKeyPath so I put the variable name of "myBoolean."

I set up the boolean to be false before then add the observer, then make the boolean to be true. It does not give me the NSLog for "changed detected"

What is the proper way of using KVO?

Lucky
  • 579
  • 6
  • 24
  • I think it works with setter and getter method of iVar. see this link http://stackoverflow.com/questions/24969523/simple-kvo-example for more detail. – Hardik Shekhat Jan 07 '16 at 07:28

2 Answers2

0

Instead of using

[self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionNew context:nil];

use

[self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionInitial context:nil];

It will work perfectly.

darshan
  • 1,115
  • 1
  • 14
  • 29
0

using both:

[self addObserver:self forKeyPath:@"myBoolean" options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial) context:nil];
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
Leon.Yue
  • 38
  • 6