Arjun
Arjun

Reputation: 89

Objective-C: Get Selected Value from UISwitch

The following code is not behaving as I would expect. I think it may have to do with not handling BOOL and NSNumber correctly or possibly I am not storing a number as a user default correctly. In any case, after getting a value from a UISwitch and trying to save it to user defaults, I am not getting value I thought I was saving.

NSNumber * on = [NSNumber numberWithBool:self.onSwitch.on];
BOOL onBool = [on boolValue];
NSLog(@"onBool before save%d",onBool);//Logs as 0
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setBool:onBool forKey:@"on"];//
[prefs synchronize];
BOOL onDefault = [[NSUserDefaults standardUserDefaults] objectForKey:@"on"];
NSLog(@"value of on after save%d",onDefault);//logs as 1

Can anyone see where I have made the error?

Upvotes: 0

Views: 348

Answers (2)

sooper
sooper

Reputation: 6039

In addition to the accepted answer, I wanted to provide a little insight into what's going on here. You're setting a Boolean but asking for an Object. You're seeing 1 (true) because the method returns an object and by casting it to a boolean it will simply check for it's existence.

Upvotes: 0

Evgeny Karkan
Evgeny Karkan

Reputation: 9612

The main idea is to use appropriate boolForKey API, so instead of

BOOL onDefault = [[NSUserDefaults standardUserDefaults] objectForKey:@"on"];  

try it like this:

BOOL onDefault = [[NSUserDefaults standardUserDefaults] boolForKey:@"on"];  

From Apple docs

boolForKey:
Returns the Boolean value associated with the specified key.

Upvotes: 2

Related Questions