Reputation: 135
A similar question on stackoverflow yielded a combination of:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
and
BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
I've been trying to look into NSUserDefaults, but I understand neither what these pieces of code do, or where they should be in my program.
Could anyone tell me where they need to go? Why doesn't the code below work?
- (void)viewDidLoad
{
[super viewDidLoad];
BOOL switchState = [[NSUserDefaults standardUserDefaults] boolForKey:@"mySwitchValueKey"];
if (switchState == YES) {
[hard1ON setOn:TRUE];
} else {
[hard1ON setOn:FALSE];
}
}
- (IBAction)switchValueChanged
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
if (hard1ON.on) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange2" object:nil];
}
}
Upvotes: 0
Views: 154
Reputation: 46543
These two statements are used to create an instance of NSUserDefaults
and then setting the switchState
in standardUserDefaults
, that is with your app.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
switchState
must be declared anywhere above this statement as BOOL switchState
.
From this statement BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
the boolValue is read back into swichState.
The above code should be in the method that is invoked when you change or flip or move to aother view, assuming switchState is an local property to a class.
If it is a global or shared it can be any where, most suitable place would be applicationSholdTerminate:
.
Upvotes: 1
Reputation: 14118
For more details check this link, it might give you brief description about NSUserDefaults.
Hope this helps.
Upvotes: 0