0

I want to add KVO notification to one of the properties of controller so that whenever there is a change in that property, observeValueForKeyPath method is invoked in the same controller.Here is what I am trying to do :

@interface ViewController ()

@property(strong, nonatomic)NSString *currentState;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _currentState = @"Active";
    [self addObserver:self forKeyPath:@"currentState" options:NSKeyValueObservingOptionNew context:NULL];
}


-(IBAction)changeState:(UIButton *)sender{
    if([_currentState isEqualToString:@"Active"])
        _currentState = @"Inactive";
    else
        _currentState = @"Active";
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString: @"currentState"]) {
        NSLog(@"State Changed : %@",_currentState);
    }

But this method observeValueForKeyPath is not getting invoked at all on button click. I searched for more examples on it, but all of them used objects of two different classes to demonstrate it. My question here is :

  1. Can KVO notifications be used in the way I am trying to i.e. on same object ?
  2. If yes, what's the problem with the code above ?

Any help would be appreciated.

ArG
  • 637
  • 1
  • 7
  • 12

1 Answers1

2

The notification is not triggered because you modify the instance variable directly, instead of using the property accessor methods:

-(IBAction)changeState:(UIButton *)sender{
    if([self.currentState isEqualToString:@"Active"])
        self.currentState = @"Inactive";
    else
        self.currentState = @"Active";
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382