NSInteger boot = [defaults1 integerForKey:@"firstBoot"];
will return 0 until you have saved a value in your defaults. 0
, NO
or nil
are returned for keys that don't have any values stored.
The correct way to handle this is to register default values before you try to retrieve these user defaults.
// register default values. until you save your own value "firstBoot" will return YES
// you should put these two lines in the `application:didFinishLaunchingWithOptions:`
// method of the AppDelegate. Add all userdefaults that should have default values there
NSDictionary *defaultUserDefaults = @{ @"firstBoot" : @YES };
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultUserDefaults];
// use BOOL instead of integer
BOOL firstBoot = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstBoot"];
if (firstBoot) {
NSLog(@"first launch");
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstBoot"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else {
NSLog(@"has been launched before");
}