I have an app that uses [NSUserDefaults standardUserDefaults] to store session information. Generally, this information is checked on app launch, and updated on app exit. I have found that it seems to be working unreliably in iOS 8.
I am currently testing on an iPad 2, although I can test on other devices if need be.
Some of the time, data written before exit will not persist on app launch. Equally, keys removed before exit sometimes appear to exist after launch.
I've written the following example, to try and illustrate the issue:
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *_dataArchive = [[NSUserDefaults standardUserDefaults]
objectForKey:@"Session"];
NSLog(@"Value at launch - %@", _dataArchive);
NSString *testString = @"TESTSTRING";
[[NSUserDefaults standardUserDefaults] setObject:testString
forKey:@"Session"];
[[NSUserDefaults standardUserDefaults] synchronize];
_dataArchive = [[NSUserDefaults standardUserDefaults]
objectForKey:@"Session"];
NSLog(@"Value after adding data - %@", _dataArchive);
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Session"];
[[NSUserDefaults standardUserDefaults] synchronize];
_dataArchive = [[NSUserDefaults standardUserDefaults]
objectForKey:@"Session"];
NSLog(@"Value before exit - %@", _dataArchive);
exit(0);
}
Running the above code, I (usually) get the output below (which is what I would expect):
Value at launch - (null)
Value after adding data - TESTSTRING
Value after deleting data - (null)
If I then comment out the lines that remove the key:
//[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Session"];
//[[NSUserDefaults standardUserDefaults] synchronize];
And run the app three times, I would expect to see:
Value at launch - (null)
Value after adding data - TESTSTRING
Value after deleting data - TESTSTRING
Value at launch - TESTSTRING
Value after adding data - TESTSTRING
Value before exit - TESTSTRING
Value at launch - TESTSTRING
Value after adding data - TESTSTRING
Value before exit - TESTSTRING
But the output I actually see is:
Value at launch - (null)
Value after adding data - TESTSTRING
Value after deleting data - TESTSTRING
Value at launch - (null)
Value after adding data - TESTSTRING
Value after deleting data - TESTSTRING
Value at launch - (null)
Value after adding data - TESTSTRING
Value after deleting data - TESTSTRING
e.g. It seems to not be updating the value on exiting the app.
EDIT: I have tested the same code on an iPad 2 running iOS 7.1.2; and it appears to work correctly every time.
TLDR - In iOS 8 does [NSUserDefaults standardUserDefaults] work unreliably? And if so is there a workaround/solution?