Goal C: How to Install a Key in NSUserDefault

I am trying to store information in NSUserdefault. My intention is to show a pop-up message to the user if he is launching the application for the first time. My code is as follows:

//In my view did load method self.prefs = [NSUserDefaults standardUserDefaults]; self.firstTimeLaunchingApp = [prefs integerForKey:@"firstTimeLaunchx"]; [self tableRefresh]; //This method is called after the refresh button is clicked -(void)tableRefresh { [self displayFirstTimeMessage]; //Other codes ommited } //Method to display pop up if first time user -(void) displayFirstTimeMessage { if (self.firstTimeLaunchingApp != 1 ) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Welcome!" message:@"Thanks for using the app!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; [prefs setInteger:1 forKey:@"firstTimeLaunchx"]; [prefs synchronize]; } } 

The problem I encountered is that the first time the application starts, a warning popup appears (as expected), however, when I click the update button (which launches "displayFirstTimeMessage" again), I still see the warning popup which was not so expected. Is there something wrong with the way I set the key for NSUserDefault?

Note. If I stopped and restarted the application, a popup will not appear.

+6
source share
1 answer

self.firstTimeLaunchingApp initialized to viewDidLoad . After saving the key, you did not update its value. Therefore, when a method is called again, its value is not 1. It still contains the value that was read earlier. There are no problems in saving, because after restarting you do not see a warning. Do it:

 [prefs setInteger:1 forKey:@"firstTimeLaunchx"]; [prefs synchronize]; // add this line self.firstTimeLaunchingApp = [prefs integerForKey:@"firstTimeLaunchx"]; 
+11
source

Source: https://habr.com/ru/post/890130/


All Articles