如何检查变量是否在目标c中每秒或更少变化?

Jam*_*mes 2 iphone function objective-c

当我点击按钮时,我正在使用if语句来检查BOOLEAN的值.单击按钮时,如果值为false,我想显示UIActivityIndi​​cator,如果值为true,我想推送新视图.我可以做得很好,但我希望当BOOLEAN成为真时,如果用户已经点击了按钮,视图会自动更改.

所以我的问题是你如何检查一个值是否每隔一秒或更少变化?

Ale*_*lds 12

查看KVO - 键值观察 - 在变量更改其值时触发操作.

-viewWillAppear:例如,在视图控制器的方法中,添加观察者:

[self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionNew context:nil];
Run Code Online (Sandbox Code Playgroud)

在您的-viewWillDisappear:方法中,取消注册观察者:

[self removeObserver:self forKeyPath:@"myBoolean"];
Run Code Online (Sandbox Code Playgroud)

执行此最后一步非常重要,这样该-dealloc方法不会抛出异常.

最后,设置观察者方法,以便在发生更改时执行以下操作myBoolean:

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"myBoolean"]) { 
        // The BOOL value of myBoolean changed, so do something here, like check
        // what the new BOOL value is, and then turn the indicator view on or off
    }
}
Run Code Online (Sandbox Code Playgroud)

当对象的值在某处发生变化时,键值观察模式是一种很好的通用方法.Apple撰写了一篇很好的"快速入门"文档来介绍这个主题.