How do you check if a variable has changed every second or less in lens c?
I am using an if statement to check for the BOOLEAN value when I click a button. When the button is clicked, if the value is false, I want to display the UIActivityIndicator, and if the value is true, I want to click the new view. I can do it well, but I want the view to automatically change when BOOLEAN becomes true if the user has already pressed the button.
So my question is, how do you check if the value of everysecond has changed or less?
a source to share
Look at KVO - Key Values Observation - to trigger an action when a variable changes its value.
In your view, the controller -viewWillAppear:
, for example, adds an observer:
[self addObserver:self forKeyPath:@"myBoolean" options:NSKeyValueObservingOptionNew context:nil];
In your method, -viewWillDisappear:
unregister the observer:
[self removeObserver:self forKeyPath:@"myBoolean"];
It is important to take this last step so that the method -dealloc
does not throw an exception.
Finally, set up an 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 observation pattern is a good, general way to trigger something when the value of an object changes somewhere. Apple has written a good "quick start" that introduces this section.
a source to share
Have a look at Key-Value Observing (often referred to simply as KVO). It uses language dynamic introspective capabilities to implement exactly this function for you.
a source to share