Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: How to set key in NSUserDefault

I am trying to store information in NSUserdefault. My intention is to show a pop up message to the user if it is the first time he/she is launching the app. 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 issue I am facing here is that when I first launch the app, the alert popup appears (which is as expected), however when I click on the refresh button (which will trigger the "displayFirstTimeMessage" again), I still see the alert popup which is not as expected. Is there something wrong with the way I am setting the key for NSUserDefault?

Note: If I stop and relaunch the app, the popup does not appear.

like image 975
Zhen Avatar asked Jun 09 '11 10:06

Zhen


1 Answers

self.firstTimeLaunchingApp in initialized in viewDidLoad. After saving the key you have not refreshed it's value. So when the method is called again, its value is not 1. It is still containing the value which was read before. There is no problem in saving, as after re-launching you are not seeing the alert. Do this:

[prefs setInteger:1 forKey:@"firstTimeLaunchx"]; 
[prefs synchronize];

// add this line
self.firstTimeLaunchingApp = [prefs integerForKey:@"firstTimeLaunchx"];
like image 98
taskinoor Avatar answered Oct 13 '22 15:10

taskinoor