Weston
Weston

Reputation: 1491

How can I receive notifications that a cocoa binding value has changed?

I am just learning Cocoa Bindings, but I have hit a snag. Is there a way to invoke a method when the value of a binding changes?

Example:

I am binding an NSStepper to NSUserDefaults to set an int, but I need to be able to update some other things when the int is changed. Is there a way to receive a notification directly from the object controller? Or should I somehow be observing the NSStepper?
If so, how do I go about that? IB doesn't seem to like me messing with it when its already bound.

Upvotes: 3

Views: 997

Answers (2)

Andrew Madsen
Andrew Madsen

Reputation: 21373

You can use Key Value Observing (KVO) to observe NSUserDefaults directly. Sign up for notifications like so:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults addObserver:self forKeyPath:@"YourUserDefaultsKey" options:0 context:NULL];

Then implement this, and it will be called whenever the value for @"YourUserDefaultsKey" changes:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (object == userDefaults && [keyPath isEqualToString:@"YourUserDefaultsKey"]) {
        int intValue = [userDefaults intValueForKey:@"YourUserDefaultsKey"];
        // Do whatever you need to do with new intValue
    }
}

Finally, don't forget to unregister as an observer wherever it's appropriate (e.g. in -dealloc):

- (void)dealloc
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObserver:self forKeyPath:@"YourUserDefaultsKey"];
}

Note that Cocoa Bindings itself is based on KVO.

Disclaimer: I typed all the code in this answer in the browser. It should be correct, but may have a typo or two.

Upvotes: 4

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

If you remember Notifications, notification center, observers, @selector:, then your work is done.

EDIT:

You can observe the changes of int, through its class. Its upto you, how you are implementing it, though IB or through code.

Upvotes: 0

Related Questions