문제

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.

도움이 되었습니까?

해결책

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];

다른 팁

Don't forget to call [userDefaults synchronise].

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top