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 :
- Can KVO notifications be used in the way I am trying to i.e. on same object ?
- If yes, what's the problem with the code above ?
Any help would be appreciated.