I need to set a slider in preferences window of a cocoa application.
If I set the NSSlider in awakeFromNib like so
-(void)awakeFromNib{
[thresholdSlider setInValue:9];
}
the preference window updates with the value when opened.
Though, since it is a preference window, I need to register the Value with NSUserDefault, so when the application at launch would run :
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
[thresholdSlider setValue:[NSUserDefaults standardUserDefaults] forKey:kthresh];
NSLog( @"%@",[thresholdSlider objectValue]);
}
But I cant even set the slider value in the applicationDidFinishLaunching method
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
[thresholdSlider setIntValue:9];
NSLog( @“%d”,[thresholdSlider intValue]);}
returns 0 and slider is set to minimum value(set in IB) in the preferences window.
Where can I call the [thresholdSlider setValue:[NSUserDefaults standardUserDefaults] forKey:kthresh];
to get the slider updated with the user value on last application quit?
The code edited according to Vadian proposition :
+(void)initialize{
NSDictionary *dicDefault = @{@"kthresh":@9};
[[NSUserDefaults standardUserDefaults]registerDefaults:dicDefault];}`
`- (void)applicationDidFinishLaunching:(NSNotification*)aNotification{
`//Preferences
NSInteger thresholdValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"kthresh"];`
thresholdSlider.integerValue = thresholdValue;}`
`-(void)applicationWillTerminate:(NSNotification *)notification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:thresholdSlider.integerValue forKey:@"kthresh"];
[defaults synchronize];}`
In AppDelegate as soon as possible register the key value pair with a default value. This value is always used if no custom value has been written to disk yet.
NSDictionary *defaultValues = @{@"kthresh" : @9};
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
Then set the value of the slider wherever you want, consider the syntax
NSInteger thresholdValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"kthresh"];
thresholdSlider.integerValue = thresholdValue;
To write the value to disk use this
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults] ;
[defaults setInteger:thresholdSlider.integerValue forKey:@"kthresh"];
[defaults synchronize];
Do not use
setValue:forKey:
andvalueForKey:
to talk toNSUserDefaults
Alternatively use Cocoa bindings and bind the key integerValue
to the NSUserDefaultsController
instance in Interface Builder.