有一种很好的方法来检查变量在连续更改一段时间后是否停止更改其值?

时间:2019-02-15 10:23:05

标签: ios objective-c asynchronous time nstimer

我正在尝试检查声明为的变量     @property (assign, nonatomic) NSTimeInterval rate;作为计时器不断变化。换句话说,随着时间的流逝,变量的值不断变化,我知道我可以在 - (void)observeValueForKeyPath:...}函数用于观察变量何时更改其值,但是我还需要知道变量何时停止更改并变为常量。我尝试了一种方法,该方法只是在此处使用NSTimer后在非常短的时间(例如0.00001秒)后检查变量的值

    - (void) checkPlaying:(NSTimer*)t {

        NSLog(@"%f %f", self.keepRate, (double)self.rate);
        return self.keepRate != (double)self.rate;
    }


    - (void) isPlaying{

    self.keepRate = (double)self.rate;
    [NSTimer scheduledTimerWithTimeInterval:0.00001
                                     target:self
                                   selector:@selector(checkPlaying:)
                                   userInfo:nil
                                    repeats:NO];
   }

并将其与先前存储的值进行比较,但这也不起作用; self.keepRate(double)self.rate;的值在该NSLog中仍然相同。我以为它将在0.00001秒后调用checkPlaying,但是我可能会误解。有人可以帮忙吗?或者,如果有人只是想出一个检查变量何时停止更改的想法也可能很好。谢谢

编辑:实际上,该变量在用户按下按钮时开始更改其值,并且在用户按下相同按钮后将停止更改值。这就是为什么我想也许我可能需要0.0001秒钟才能检查变量的值是否已更改。我知道我可以使用按钮检查值是否正在更改,但是如果这样做,还有很多其他问题和事情要处理,这就是为什么我问这个问题。

1 个答案:

答案 0 :(得分:0)

这是类声明

@interface MyClass : NSObject

@property (nonatomic) int keepRate;

@end

下面是实现

@implementation MyClass
- (void)setKeepRate:(int)aKeepRate {
    int oldValue = _keepRate;
    if (oldValue == aKeepRate) {
        // The value is same as before, that means the value is constant now
        // Do whatever you want to do now
    }
    // Update underlaying variable with new value, regardless if it is same or not
    _keepRate = aKeepRate;
}
@end

您也可以对费率进行同样的操作