NSUserDefaultsController & NSNotification

Posted:
in Genius Bar edited January 2014
I'm still a very new Cocoa programmer and I have a question about the NSDefaultsController.



Background:

I have a pref panel that takes several float values and stores them in the preferences database. I'm using an instance of NSUserDefaultsController to handle that, and its working well. The main app window then uses these values to calulate a weight and balance figure.



Problem:

The main app window reads the values out of preferences just fine when it starts, but if the preference values are changed while the app is running, you have to quit the app and restart for it to use the new values. I figure the answer lies in a notification. I guess I need to post a notification when a value is changed in the prefpane. Can NSUserDefaults controller do this? Also, how do I update the main window once I receive the notification?



Thanks

Comments

  • Reply 1 of 1
    costiquecostique Posts: 1,084member
    Do you use it like this:
    Code:


    float var;

    var = [[[NSUserDefaults] standardUserDefaults] floatForKey:@"MyVar"];



    Note that this code snippet copies the value into var, so when your preferences change, the var does not, because after copying these values are totally independent.



    You have options, though:

    a) Everywhere you use var, just send [[[NSUserDefaults] standardUserDefaults] floatForKey:@"MyVar"]. This will bloat your code like hell, but will work.

    b) Set your scalar variables twice: when you read the prefs at launch time and when you show/close the prefs window/panel/sheet. Since it's logical to modify prefs only in the prefs panel, it's also logical to set your variable there. This will ensure consistency between NSUserDefaults instance and the values of your variables like var.

    c) Use notifications. However, if implemented properly, you will post the notification only twice: at launch time when you read prefs and when a user modifies them through your prefs UI. You register a method for this notification, in which you sync your variables to NSUserDefaults. Essentially, it's the same as b).
Sign In or Register to comment.