简体   繁体   中英

How to retrive the value from NSUserDefault before my app loads…?

Im having a ViewController on which on clicking a button, label gets updated. I want is, each time the app opens it should retain its old value. Im able to write every value in NSUserDefault but not getting how to write the value on label before the app loads.
Example:
In first run the label is having the value 5. In second run the label should contain the same value 5, and if i made any changes that change should be there in third run.
Thanx...

In your AppDelegate, the very first method gets called after launching an App is,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    return YES;
}

and for other cases such as from inactive to active state of your application use,

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

I recommend Reading, Apple's iOS application lifecycle documentation .

Here's how to retrieve a stored value from NSUserDefaults and set the value for your label when your ViewController loads:

- (void)viewDidLoad
{
    [super viewDidLoad];    
    self.myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"mySavedValue"];
}

I'm assuming your button is already hooked up to an action something like this that will save the value to the standardUserDefaults when clicked:

- (IBAction)buttonPressed:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.myLabel.text forKey:@"mySavedValue"];
    [defaults synchronize];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM