NSUserDefaults, do something on first load only

笑着哭i 提交于 2019-12-18 07:04:49

问题


I'm trying to do show an alert the first time the app is launched. I'd also like to show this alert if they go into a settings page later on and want to see it again. I figured I could set a boolean in the NSUserDefaults. I'm not quite sure how to do that though (assuming this approach is right). I thought in applicationDidFinishLaunching:options, I could get the value for key @"FirstTimeLaunched", and in applicationWillTerminate, I could set the object for that key to NO. If this is the case, how do I get the BOOL to be YES for the first time?

Also, do I need to set it to NO in didEnterBackground mode as well? Thanks.


回答1:


Just think it backwards, instead of expecting a YES, set a variable when the app is actually launched, and remove it when the user says so in the settings.

At launch:

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"hasBeenLaunched"]) {
    // show your only-one-time view
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasBeenLaunched"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

And when the user wants to see it again, just remove the key:

[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"hasBeenLaunched"];

When accessing a key that does not exists, NSUserDefaults will return nil.




回答2:


I would take the opposite approach and first launch check for a key called appHasLaunchedPreviously.

If it's yes then bypass the alert. If it's not YES then show the alert and immediately set it ready for next time.




回答3:


First time App is launched, so I don't think you will ever need to set that BOOL to NO. UserDefaults gets deleted if App is removed. and we set it when App is first launched application didFinishLaunchingWithOptions:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"FirstTimeLaunched"];
[[NSUserDefaults standardUserDefaults] synchronize];

If you set Bool to NO in applicationWillTerminate, then everytime user kills app from tray you will show alert on app launched. Again it depends on your business requirements.



来源:https://stackoverflow.com/questions/7983411/nsuserdefaults-do-something-on-first-load-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!