NSUserDefaults, do something on first load only

前端 未结 3 1166
暗喜
暗喜 2020-12-20 01:11

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

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 01:43

    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.

提交回复
热议问题