Use Settings With NSUserDefaults

With the NSUserDefaults class, you can save settings and properties related to application or user data. Any data saved to the defaults system will persist through application restarts. In this tutorial we will save the state of a switch, so this state is saved when the app restarts.

Open Xcode and create a new Single View Application. For product name, use UserDefaultsDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox and Use Automatic Reference Counting checkbox are selected.

Go to the MainStoryboard. Drag a label to the main view and place it on the left side. Drag a switch to the view and align it next to the label. The main View should look like this.

Build and Run, and change the switch to Off. Exit the application and start it again. As you can see the previously selected state isn't persistent through application restarts. Let's implement this feature.

Select the Assistant Editor and open ViewController.m. Ctrl and drag from the switch to the interface section and create a outlet.

Ctrl and drag from the switch to the interface section to create a action.

The interface section of ViewController.m now contains the following code.

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UISwitch *bluetoothSwitch;

- (IBAction)saveSwitchState:(id)sender;


Next, implement the changeSwitchState IBAction method

- (IBAction)saveSwitchState:(id)sender 
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

  if ([self.bluetoothSwitch isOn])
    [defaults setBool:YES forKey:@"SwitchState"];
    [defaults setBool:NO forKey:@"SwitchState"];
We create a NSUserDefaults object, where we can save the user settings. Next, we save the current switch state as a Boolean value in the Switchstate key. Next, change the  method viewDidLoad
- (void)viewDidLoad 
  [super viewDidLoad];

  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

  if ([defaults objectForKey:@"SwitchState"])           
    self.bluetoothSwitch.on = [defaults boolForKey:@"SwitchState"];
We check if there is a previously created SwitchState key, and if so we load the state and change the switch. Build and Run, change the switch state to Off. Restart the application and you will see the switch still is in the off state.

You can download the source code of the UserDefaultsDemo at the ioscreator repository on github.