observeValueForKeyPath

时间:2016-01-26 01:27:26

标签: ios key-value-observing

我的倒计时从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永远不会被调用。

1 个答案:

答案 0 :(得分:0)

我发现您不会在块中更新变量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;
};