iOS NSUserDefaults plist files are losing changes

2019-10-06 17:43发布

问题:

We are facing an unusual scenario where my app's plist get set to default values automatically ,mostly after restarting the ipad/iphone. Any ideas on why this happening?

We are reading the plist like this

[[NSUserDefaults standardUserDefaults] registerDefaults:[AppSetting globalConfig]];

+ (NSDictionary *) globalConfig {
    NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"];
    return [[[NSDictionary alloc] initWithContentsOfFile:plistPath] autorelease];
}

And after saving we write it off with

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];   
[defaults setBool:self.isLogIn forKey:@"isLogin"];
[[NSUserDefaults standardUserDefaults] synchronize];

some more edits... does this have any thing to do with this automatic restore. i am seeing this line in the ipads who's plist was restored..

<Error>: HID: The 'Passive' connection 'appName' access to protected services is denied.
<Error>: HID: The 'Rate Controlled' connection 'appName' access to protected services is denied.

回答1:

Your app is writing to NSUserDefaults without ever calling synchronize . The app goes to the background, and crashes for some reason (or just crashes outright) - so the changes meant to be saved to NSUserDefaults never are, and it appears your plist file is reverting when it was just never saved. It could be powering off the devices kill the apps in a way that is not allowing the save of NSUserDefaults changes.

OR are you writing to the NSUserDefaults plist files without going through NSUserDefaults? Don't do that.

OR the testers are testing on multiple devices with the same iCloud account on both that are synchronizing the UserDefaults plist files between devices for your app.

Edit: Why are you reading settings from the read-only app bundle and using NSUserDefaults to save changes? They will not do the same thing. You will never be reading wheat NSUserDefaults is writing to.