NSUserDefaults - storing and retrieving data

16,827

Solution 1

Put this text in

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"];
    NSLog(@"Value from standardUserDefaults: %@", aValue);

    NSLog(@"Label: %@", myLabel);
    myLabel.text = aValue;
}

And in your "edit" view in - viewWillDisappear: save changes in NSUserDefaults

Solution 2

When saving data to NSUserDefaults, it doesnt immediately write to the Persistent Storage. When you save data in NSUserDefaults, make sure you call:

[[NSUserDefaults standardUserDefaults] synchronize];

This way, the value(s) saved will immediately be written to Storage and each subsequent read from the UserDefaults will yield the updated value.

Solution 3

Do not forget the use synchronize when you set some value

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:YOUR_VALUE forKey:@"KEY_NAME"];
[defaults synchronize];

Now you can place your code in viewWillAppear method to retrieve the value from defaults, this will help you fetch the currentsaved value for your desired key.

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* strValue =    [defaults objectForKey:@"KEY_NAME"];
myLabel.text = strValue != nil ? strValue : @"No Value";

Hope it helps

Share:
16,827

Related videos on Youtube

hanumanDev
Author by

hanumanDev

Updated on June 05, 2022

Comments

  • hanumanDev
    hanumanDev almost 2 years

    I have some data that's been stored using NSUserDefaults in one view and then being displayed in another view. The issue I'm having is that when the user changes the data and then returns to the view where the data is displayed (in a UILabel), the data that was first saved is displayed instead of the newer saved text.

    I think I need to do something with viewDidAppear perhaps, so that every time the view appears the newest saved data is displayed.

    here's the code that Im displaying the NSUserDefaults stored info on a UILabel:

       NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"];
        NSLog(@"Value from standardUserDefaults: %@", aValue);
    
        NSLog(@"Label: %@", myLabel);
        myLabel.text = aValue;
    

    if someone could point me in the right direction that would be great,

    thanks

  • Matthias Bauch
    Matthias Bauch over 12 years
    the second part of the second part is not true. NSUserDefaults always reads from its cache first. And if you save something it is written to the cache immediately. The need for synchronize after each write to NSUserDefaults is an urban myth among iPhone developers.