I have a public variable in my Objective-C++ AppDelegate called stepsCompleted
, so I access it in my table view controller with [AppDelegate instance]->stepsCompleted
.
I want my table view controller to tell me when the value of that variable has changed, so I do the following in the initWithCoder:
method that I know is being called:
[self addObserver:self forKeyPath:@"[AppDelegate instance]->stepsCompleted" options:0 context:NULL];
However, despite me changing stepsCompleted
constantly in the AppDelegate, my method:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
}
Is never called.
What exactly am I doing wrong?
There are different problems with your code. First of all, Key-Value Observing is a mechanism to observe properties of an object. It does not work with instance variables. So you should declare "stepsCompleted" as a property of the application delegate instead of an instance variable:
@property (nonatomic) int stepsCompleted;
and set its value through the property accessor methods, e.g.
[AppDelegate instance].stepsCompleted = newValue;
Next, "[AppDelegate instance]->c"
is not a key path, and you have to specify at least one observing option, e.g. NSKeyValueObservingOptionNew
.
To observe the "stepsCompleted" property of [AppDelegate instance]
, it should be
[[AppDelegate instance] addObserver:self
forKeyPath:@"stepsCompleted"
options:NSKeyValueObservingOptionNew
context:NULL];