NSUserDefaults refuse to save

空扰寡人 提交于 2019-12-04 16:53:05

This is normal behavior.

User defaults get queued to save. When you "force quit" the app you're not giving it time to do that.

I assume that on Xcode you mean hitting stop. And you mention exit(0);. Neither of things are "normal" to an iOS app. This type of force quitting should not be done in an iOS app.

When the user quits an app the normal way (multi-task view and sliding the app up) it doesn't actually quit right then. It removes from view as if it does. But the user defaults will then get written out after that. Up to several seconds after. Same when they hit the home button.

The documentation completely explains the app life cycle. Use the messages. And you should force flush out the defaults when these messages are received. Put in your initialization or ViewDidLoad like this:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movingToBackground:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movingToForeground:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDefaults:) name:UIApplicationWillTerminateNotification object:nil];

Then create the methods movingToBackground, movingToForeground, and updateDefaults like this:

-(void) updateDefaults: (NSNotification *) notification {
     [[NSUserDefaults standardUserDefaults] synchronize];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!