Search code examples
objective-cmacoscocoansbutton

setState not updating a checkbox's view


I'm trying to create a preferences window.
In it I have some checkbox style NSButtons. The problem is that they aren't updating when I call the setState: method. I access the standarUserDefaults when then window is initialized to get the state they should be in and was planning to change them depending on what state that key is in.

I know that they are in fact connected to both their IBOutlet and IBAction as I've tried some NSLog-ing to make sure of that.

I read something about Changing the value of a model property programmatically is not reflected in the user interface here but I'm not sure if that's the problem or frankly what they are referring to there.

I declared the checkbuttons in the .h file like so:

IBOutlet NSButton *defaultDateCheck;
IBOutlet NSButton *closeOnCreationCheck;
IBOutlet NSButton *allowEmptyNumberCheck;
IBOutlet NSPopUpButton *defaultJobSetting;

The init method looks like this:

-(id)initWithWindowNibName:(NSString *)windowNibName{

    self = [super initWithWindowNibName:windowNibName];

    if (self) {

        NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];

        [defaultDateCheck setState:[myDefaults boolForKey:@"useDefaultDate"]];

        [closeOnCreationCheck setState:[myDefaults boolForKey:@"closeOnCreation"]];

        [allowEmptyNumberCheck setState:[myDefaults boolForKey:@"allowEmptyProjectNumber"]];

        [defaultJobSetting selectItemAtIndex:[myDefaults integerForKey:@"defaultJob"]];
    }
    return self;
}

I also tried the following format for setting the checkboxes but with no result:

if ([myDefaults integerForKey:@"useDefaultDate"] == YES) {
    [defaultDateCheck setState:NSOnState];
}
else {
    [defaultDateCheck setState:NSOffState];
}

The connected IBAction methods for the checkboxes looks like this:

-(IBAction)toggleCloseOnCreation:(id)sender{
    [[NSUserDefaults standardUserDefaults] setBool:([closeOnCreationCheck state] == NSOnState) forKey:@"closeOnCreation"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Solution

  • Set the state in -viewDidLoad method since in -init the view and it's subviews do not exist yet