Search code examples
iosobjective-cnsuserdefaultsuipickerview

Save data from UIPickerView in NSUserDefaults based on user selection and call it in another ViewController Objective-C


This is my problem. In one ViewController there are two PickerViews which have data taken from a server and shown on the rows of the pickerView.

What I want to do is to save in the NSUserDefaults the data shown on the row selected by the user (in this case is an int) and use it in another ViewController inside a function.

Now I'm saving it in this way:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSMutableArray<Wallet *> *userWallets = [DB_SINGLETON getAllWallets];

if (pickerView.tag == 1) {
    switch (row) {
        // Select a merchant and save data in UserDefaults and call it back when I send the message in SendMsgToOperatorViewController
        case 1:
            break;
        case 2:
            [[NSUserDefaults standardUserDefaults] setInteger:userWallets[0].walletid forKey:@"merchantSelected"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            NSLog(@"");
        case 3:
            [[NSUserDefaults standardUserDefaults] setInteger:userWallets[1].walletid forKey:@"merchantSelected"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        default:
            break;
    }
} else if (pickerView.tag == 2) {
    // code
    }
}

I would like to save the data in NSUserDefaults based on which row is selected by the user. Can this be a correct way to do it?


Solution

  • Better solution would be -

    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSMutableArray<Wallet *> *userWallets = [DB_SINGLETON getAllWallets];
    
    if (pickerView.tag == 1) && row > 1 {
    // Skipping first 2 rows since qustion also skips it
      [[NSUserDefaults standardUserDefaults] setInteger:userWallets[row-2].walletid forKey:@"merchantSelected"];
      [[NSUserDefaults standardUserDefaults] synchronize];
    } else if (pickerView.tag == 2) {
        // code
        }
    }