How to use NSUserDefaults to save state of switch?

How to use NSUserDefaults to save state of switch?

If you have an application that should save for example state of a switch and you don’t want use database for that small request you can simply add instance of NSUserDefaults class in your implementation. It is easy job, see below;

- (IBAction) saveState {
 
NSString *value = @"ON";
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
if(!switch.on){
value = @"OFF";
[userPreferences setObject:value forKey:@"stateOfSwitch"];
}
[userPreferences setObject:value forKey:@"stateOfSwitch"];
 
}

This is part of code that loads value in a NSString *value for key stateOfSwitch. When you start your application again and view finisheds with loading button will be in lefted state.

- (void)viewWillAppear:(BOOL)animated {
 
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:@"stateOfSwitch"];
 
if([_value compare:@"ON"] == NSOrderedSame){
switch.on = YES;
}
else {
switch.on = NO;
}
[super viewWillAppear:animated];
}

NSUserDefaults class gives us an opportunity to save values without database use. This class uses KVC structure model for saving and loading values. Key-value coding (KVC) defines generic property accessor methods—valueForKey: and setValue:forKey:—which identify properties with string-based keys.

KVC is not meant as a general alternative to using accessor methods—it is for use by code that has no other option, because the code cannot know the names of the relevant properties at compile time. Key-value coding and the dot syntax are orthogonal technologies. You can use KVC whether or not you use the dot syntax, and you can use the dot syntax whether or not you use KVC. Both, though, make use of a “dot syntax”.

In the case of KVC, the syntax is used to delimit elements in a key path. It is important to remember that when you access a property using the dot syntax, you invoke the receiver ’s standard accessor methods (as a corollary, to emphasize, the dot syntax does not result in invocation of KVC methods valueForKey: or setValue:forKey:).

You made it all the way down here so you must have enjoyed this post! You may also like:

Apple push notifications from Magento Darko Goles
Darko Goles, | 5

Apple push notifications from Magento

Magento API v2 SOAP demystified Darko Goles
Darko Goles, | 39

Magento API v2 SOAP demystified

Develop your own Magento mobile application Ivica Tadic
Ivica Tadic, | 50

Develop your own Magento mobile application

9 comments

  1. Where in my ios code would I put these SAVE and LOAD methods… if I didn’t want to make the user hit SAVE and LOAD buttons each time?

    Just ‘load on launch’ and “save on exit’.

  2. Or this::

    static const NSString *kSwitchStateKey = @”stateOfSwitch”;

    – (IBAction) saveState {
    [NSUserDefaults standardUSerDefaults] setBool:switch.on forKey:kSwitchStateKey];
    }

    – (void)viewWillAppear:(BOOL)animated {
    switch.on = [NSUserDefaults standardUSerDefaults] boolForKey:kSwitchStateKey];
    }

  3. thanks for the info. I was curious, do you know how to save the state of a UIButton? I have an app where a UIButton is disabled when a user taps it. I just need to find a way to save the state of the button for the next time the user launches the application. Any help would be great.
    -Thank you

  4. Is there is advisable to use NSUserDefaults for an application to save UserName, Email instead of Sqlite

  5. I actually always just use setBool:forKey: to set the values of switches, since they are already BOOL’s and it just seems unintuitive to have to slap NSStrings into the mix.

    Also should be noted that there are other useful methods in NSUserDefaults:

    – setBool:forKey:
    – setFloat:forKey:
    – setInteger:forKey:
    – setObject:forKey:

    All quite self explanatory (see more here: http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html)

    1. Thanks for advice Sahil Desai! I have by mistake put “YES” and “NO” – I ment “ON” and “OFF”. That’s why I have decided to use a string. Just to show how to save state.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.