views:

128

answers:

3

I am using an if statement to check the 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?

A: 

I think you want to look into the Observer Pattern.

FrustratedWithFormsDesigner
+1  A: 

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.

Phil Nash
+6  A: 

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.

Alex Reynolds
how does this apply if the variable i want to check is in another view controller
James
Instead of sending the message addObserver to self, you send it to the other view controller.
progrmr
The use of self is not a requirement, although you want to make sure that you un-register any observers added to other objects before they are deallocated. Otherwise your app will likely crash, trying to send an "observation" to a released observer object, which no longer exists.
Alex Reynolds