Joannes
Joannes

Reputation: 81

Set NSPopUpButton at first launch

I have a NSPopUpButton but at first time launch this does not set correctly the first value. I have set awakeFromNib but the NSPopUpMenu is empty. Only the second time and the next it works correctly. Thanks in advance.

-(IBAction)chancepesoalert:(id)sender{

int selection = [(NSPopUpButton *)sender indexOfSelectedItem];
NSNumber *valore = [NSNumber numberWithUnsignedLongLong:(30*1000*1000)];


if (selection == 0) { 
    valore = [NSNumber numberWithUnsignedLongLong:(30*1000*1000)];
    NSLog(@"Selezionato 0");
} 

if (selection == 1){

    valore = [NSNumber numberWithUnsignedLongLong:(50*1000*1000)];
    NSLog(@"Selezionato 1");
}
if (selection == 2){

    valore = [NSNumber numberWithUnsignedLongLong:(75*1000*1000)];
    NSLog(@"Selezionato 2");
}
if (selection == 3){

    valore = [NSNumber numberWithUnsignedLongLong:(100*1000*1000)];
    NSLog(@"Selezionato 3");
}



NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:valore forKey:@"SetPesoAlert"];
[userDefaults synchronize];   

}


-(void)awakeFromNib {

unsigned long long value = [[[NSUserDefaults standardUserDefaults] objectForKey:@"SetPesoAlert"] unsignedLongValue];

int index;
if (value == (30*1000*1000)) {
    index =0;
}
if(value == (50*1000*1000)) {
    index =1;
}
if(value == (75*1000*1000)) {
    index =2;
}
if(value == (100*1000*1000)) {
    index =3;
}

[pesoalert selectItemAtIndex:index];

}

Upvotes: 0

Views: 1004

Answers (1)

rdelmar
rdelmar

Reputation: 104082

I sounds like you need to use registerDefaults (you might not need to do this however, since the operating system will pick default values and 0 for an index is what it will pick I think). This allows you to set up default values for the first time an app is run, but if the user changes a default, that new default will be used the next time the app is run (but you need to read those defaults at start up -- I don't see any defaults reading in the code you posted).

There is however, an even easier way to do this using bindings. When I do popups, I use an array to supply the values to the popup menu. In IB, I delete the menu items that you get by default, and then bind the popup's content binding to, for instance, App Delegate.data (data is the name of my array). Then I bind the Selected Index to the Shared User Defaults Controller with a Model Key Path of whatever (it doesn't matter what you call it, this is a name that the controller uses, it's not a property in your code). When you start the app for the first time it defaults to index=0, so you will get whatever is the first item on your list, and any changes the user makes will be remembered on the next startup.

Upvotes: 1

Related Questions