0

I am going nuts, I looked everywhere on the web but I always found the same code for KVO observing. Yet my observeValueForKeyPath: is never called; this is the simple code I use to observe UILabel taximeterValue:

-(id) initWithCoder:(NSCoder *)aDecoder{
    self=[super initWithCoder:aDecoder];
    if (self){
                [taximeterValue addObserver:self forKeyPath:@"text" options:(NSKeyValueObservingOptionNew |
                                                               NSKeyValueObservingOptionOld) context:NULL];
    }
    return self;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
if ([keyPath isEqual:@"text"]) {
    if (myBookingAlert) myBookingAlert.taximeterValue=self.taximeterValue;
    NSLog(@"the text changed");
    // put your logic here
}
// be sure to call the super implementation
// if the superclass implements it
[super observeValueForKeyPath:keyPath
                     ofObject:object
                       change:change
                      context:context];

}

Monolo
  • 18,205
  • 17
  • 69
  • 103
Fabrizio Bartolomucci
  • 4,948
  • 8
  • 43
  • 75

1 Answers1

1

A few possible explanations:

  1. taximeterValue is nil.
  2. Nothing is changing taximeterValue.text.
  3. Something is changing taximeterValue.text in a non-KVO-compliant way. Every change to taximeterValue.text must be done either by calling [taximeterValue setText:], or surrounded by appropriate willChangeValueForKey: and didChangeValueForKey: messages.
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • That is an outlet, so it may not be nil. Of course I changed it before posting this query. Also the change is done by setText. I did not employ the changeValueForKey functions, as I read they are not necessary. – Fabrizio Bartolomucci Jun 02 '13 at 18:54
  • An outlet can be nil. In fact, the outlet is probably nil during `initWithCoder:`, because outlet connections created in a nib are set *after* `initWithCoder:` returns, and before `awakeFromNib` is called. Try moving your `addObserver:…` call to `awakeFromNib`. – rob mayoff Jun 02 '13 at 20:15
  • Read about [“The Object Loading Process” in the *Resource Programming Guide*](http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html#//apple_ref/doc/uid/10000051i-CH4-SW19) for the full story. – rob mayoff Jun 02 '13 at 20:17
  • Thanks, I moved the function there and I will see if that solves the issue. – Fabrizio Bartolomucci Jun 20 '13 at 17:29