Domanda

I have a plist file with the a key APICalls of type boolean set to NO. I then retrieve this value in my code like this:

NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"DefaultSettings.plist"];
NSMutableDictionary *defaultPreferences = [NSMutableDictionary dictionaryWithContentsOfFile:destinationPath];

NSLog(@"SETUP %@", defaultPreferences);

[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

NSMutableArray *tmp = [data objectForKey:@"user"];;
user.email = [tmp valueForKey:@"email"];
user.userId = [tmp valueForKey:@"id"];
user.username = [tmp valueForKey:@"username"];
user.APICall = [NSNumber numberWithBool:[defaults objectForKey:@"APICalls"]];

NSLog(@"API Call Value: %@", user.APICall);

My first log returns :

SETUP {
APICalls = 0;
TrackingTimer = 15;
VoiceMessages = 0;

}

Showing me the value of APICalls is 0. But when I log user.APICall, I get

API Call Value: 1

Also user.APICall is of type NSNumber.

È stato utile?

Soluzione

The problem is that objectForKey: of NSUserDefaults returns a cocoa object - in this case, it is probably an NSNumber. When you pass it to numberWithBool: method, it treats nil as NO, and everything else as YES.

If APICalls is set as a boolean, you can use it directly, like this:

user.APICall = [defaults objectForKey:@"APICalls"];

If APICalls is a number that you would like to re-interpret as a boolean, you can use this line instead:

user.APICall = [NSNumber numberWithBool:[[defaults objectForKey:@"APICalls"] intValue] != 0];

Altri suggerimenti

Don't forget to call [userDefaults synchronise].

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top