KVO 有条件地触发 observeValueForKeyPath 中的方法
KVO conditionally fire method in observeValueForKeyPath
我有一个从 5 开始倒数的倒计时。我在代表倒计时的浮点数 属性 上使用 KVO
。它触发 observeValueForKeyPath
一次或根本不触发。我希望它触发 observeValueForKeyPath
直到被观察到的 属性 匹配特定值,因此它可以触发 observeValueForKeyPath
.
中的方法
请看代码
编辑
__block float progress;
self.countdown.labelVCBlock = ^(KAProgressLabel *label) {
progress = 5-(label.progress *5);
label.text = [NSString stringWithFormat:@"%.f", (progress)];
};
self.progressFloat = 5.0f; //setting the initial value
[self addObserver:self forKeyPath:@"progressFloat" options:NSKeyValueObservingOptionNew context:NULL];
self.progressFloat -= progress;//progress is a float that counts down from 5
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"progressFloat"]) {
NSLog(@"KVO called");
if (self.progressFloat < 0.1f) {//when self.progressFloat is less than 0.1 second, then fire the method below.
[self takePhoto:nil];
}
}
}
该方法要么立即触发,要么 observeValueForKeyPath
永远不会被调用。
我看到您没有更新变量 progressFloat
。尝试将代码更改为:
__unsafe_unretained typeof(self) weakSelf = self;
self.countdown.labelVCBlock = ^(KAProgressLabel *label) {
progress = 5-(label.progress *5);
label.text = [NSString stringWithFormat:@"%.f", (progress)];
weakSelf.progressFloat -= progress;
};
我有一个从 5 开始倒数的倒计时。我在代表倒计时的浮点数 属性 上使用 KVO
。它触发 observeValueForKeyPath
一次或根本不触发。我希望它触发 observeValueForKeyPath
直到被观察到的 属性 匹配特定值,因此它可以触发 observeValueForKeyPath
.
请看代码
编辑
__block float progress;
self.countdown.labelVCBlock = ^(KAProgressLabel *label) {
progress = 5-(label.progress *5);
label.text = [NSString stringWithFormat:@"%.f", (progress)];
};
self.progressFloat = 5.0f; //setting the initial value
[self addObserver:self forKeyPath:@"progressFloat" options:NSKeyValueObservingOptionNew context:NULL];
self.progressFloat -= progress;//progress is a float that counts down from 5
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"progressFloat"]) {
NSLog(@"KVO called");
if (self.progressFloat < 0.1f) {//when self.progressFloat is less than 0.1 second, then fire the method below.
[self takePhoto:nil];
}
}
}
该方法要么立即触发,要么 observeValueForKeyPath
永远不会被调用。
我看到您没有更新变量 progressFloat
。尝试将代码更改为:
__unsafe_unretained typeof(self) weakSelf = self;
self.countdown.labelVCBlock = ^(KAProgressLabel *label) {
progress = 5-(label.progress *5);
label.text = [NSString stringWithFormat:@"%.f", (progress)];
weakSelf.progressFloat -= progress;
};