开发者

Objective C: How to set key in NSUserDefault

开发者 https://www.devze.com 2023-03-11 07:01 出处:网络
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:

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 expec开发者_如何学Goted), 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.


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"];
0

精彩评论

暂无评论...
验证码 换一张
取 消