Sunday, March 15, 2015

iOS Tutorial - Part 30 - NSUserDefaults, UISwitch

NSUserDefaults, UISwitch


Video Description 

NSUserDefaults

Sometimes we want to save some small amount of data, which is mostly user preferences. For example if they choose to save their username, we should be able to save the username even if they kill the app. There is a useful API for doing this, which is NSUserDefaults. It can save some specific types. The types that NSUserDefaults can save are as follow: 1-NSString 2-NSArray 3-NSDictionary 4-NSData 5-NSDate 6-NSNumber.

Store preferences (User defaults)

If we want to save a username like HuxTek we can do it like bellow. We set a "HuxTek" value for a key "username". So whenever we want to retrieve the "HuxTek" we should call a key "username".
    [[NSUserDefaults standardUserDefaults] setValue:@"HuxTek" forKey:@"username"]
Now if we want to retrieve the username we can do something like bellow:
    [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
If we want to store a boolean value we can use the following api:
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"switchState"];
and for retrieve this boolean value we should have:
    [[NSUserDefaults standardUserDefaults] boolForKey:@"switchState"]

UISwitch

UiSwitch is a simple class with simple API. The most important APIs are as follow

isOn

If we want to check if the switch value is on or off, we can use this property like bellow:
if (self.mySwitch.isOn)
{
    //Do something when switch value is true (ON)
}
else
{
    //Do something when switch value is false (OFF)
}

setOn

In order to set the value of the switch programmatically we can use setOn api.
[self.rememberMeSwitch setOn:YES];

Download

Download this App from HERE.