Start a new single view project and update the main ViewController's viewDidLoad. The intention is to retrieve and increment a value stored in NSUserDefaults
and save it.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *key = @"kTheKey";
NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:key];
NSLog(@"current value is %@", number);
NSNumber *incremented = @(number.integerValue + 1);
NSLog(@"new value will be %@", incremented);
[[NSUserDefaults standardUserDefaults] setObject:incremented forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"reboot");
}
If I force quit the app from Xcode (or in practical use, reboot the device), the defaults are frequently not saved. Here is some sample output:
current value is (null)
new value will be 1
reboot
current value is 1
new value will be 2
reboot
current value is 1
new value will be 2
reboot
There appears to be some time component - if I wait 3+ seconds before rebooting, it is more likely the defaults will save. Note that the first execution was 'allowed' to save by waiting for a few seconds before stopping execution. The second execution was stopped in the first second or two, leading to the unchanged values logged in the the third run. This is re-produceable on my iPad Air 2 running iOS 8.1.
What could account for this?