Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple KVO example

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.

like image 485
WebOrCode Avatar asked Jul 26 '14 09:07

WebOrCode


People also ask

What is KVO used for?

KVO, which stands for Key-Value Observing, is one of the techniques for observing the program state changes available in Objective-C and Swift. The concept is simple: when we have an object with some instance variables, KVO allows other objects to establish surveillance on changes for any of those instance variables.

What is KVO in Objective-C?

Key-Value-Observing (KVO) allows you to observe changes to a property or value. To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant.

What is KVO and KVC?

KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.

What is key-value observation?

Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It's useful for communicating changes between logically separated parts of your app—such as between models and views. You can only use key-value observing with classes that inherit from NSObject .


1 Answers

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); } 
like image 100
codester Avatar answered Sep 23 '22 15:09

codester