开发者

How do you check to see if a variable has changed every second or less in objective c?

开发者 https://www.devze.com 2022-12-29 06:56 出处:网络
I am using an if statement to check th开发者_开发知识库e value of a BOOLEAN when i click on a button. When the button is clicked if the value is false i want to display a UIActivityIndicator and if th

I am using an if statement to check th开发者_开发知识库e value of a BOOLEAN when i click on a button. When the button is clicked if the value is false i want to display a UIActivityIndicator and if the value is true i want to push the new view. I can do this fine but i want the view to change automatically when the BOOLEAN Becomes true if the user has already clicked the button.

So my question is how do you check to see if a value has changed everysecond or less?


Look into KVO — Key-Value Observing — to trigger an action when a variable changes its value.

In your view controller's -viewWillAppear: method, for example, add the observer:

[self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionNew context:nil];

In your -viewWillDisappear: method, unregister the observer:

[self removeObserver:self forKeyPath:@"myBoolean"];

It's important to do this last step, so that the -dealloc method doesn't throw an exception.

Finally, set up the observer method to do something when there is a change to 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
    }
}

The Key-Value Observing pattern is a good, general way to trigger something when an object's value changes somewhere. Apple has written a good "quick-start" document that introduces this topic.


Have a look a Key-Value Observing (often referred to simply as KVO). It uses the language's dynamic introspective capabilities to implement exactly this functionality for you.


I think you want to look into the Observer Pattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消