我疯了,我在网上到处寻找,但我总是找到与KVO观察相同的代码。然而我的observeValueForKeyPath:从未被调用过;这是我用来观察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];
}
答案 0 :(得分:1)
一些可能的解释:
taximeterValue
是零。taximeterValue.text
。taximeterValue.text
。对taximeterValue.text
的每次更改都必须通过致电[taximeterValue setText:]
或在适当的willChangeValueForKey:
和didChangeValueForKey:
消息中进行。