iOS: Updating text labels with NSUserDefault data

2019-08-16 01:52发布

问题:

I have a text label on view 1 and a button. If I click the button, I am brought to view 2 through a modal connection. In this view, I enter a number and press a button. The button saves the number to NSUserDefaults, as well as tries to update the text label on view 1 to reflect this number.

Button's code:

- (IBAction)returnToView1:(UIButton *)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
defaults setObject:@"myNumber" forKey:@"myKey"];
[defaults synchronize];
_myLabel.text = [defaults stringForKey:@"myKey"];
}

However, when I go back to view 1 using a modal connection, the label never updated. I could solve this by adding the following code:

-(void)viewDidAppear:(BOOL)animated
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_myLabel.text = [defaults stringForKey:@"myKey"];
}

The problem is, view 1 first loads, and then the text field populates, so it looks unprofessional. I want the text label to populate before loading the view. I've tried placing this code inside of this method:

(void)viewWillAppear:(BOOL)animated

...but that didn't work either (for some reason the text field would only populate after I closed the app, switched to view 2, pressed the button a second time, and then returned to view 1). Thanks for any suggestions!

回答1:

However, when I go back to view 1 using a modal connection, the label never updated

There could be two possible reasons for this.

  1. You say this:

    _myLabel.text = [defaults stringForKey:@"myKey"];
    

    Well, maybe _myLabel does not point to the label back in view 1.

  2. The words "go back to view 1 using a modal connection". I hope this does not mean you are using a segue. If that is the case, you are doing a very wrong thing. You are making a new, different copy of the first view controller. So now you have two copies of the first view controller, and you changed the label in the first one but you are showing the second one on top of it.

    The way you get back from a modal segue is not to use another modal segue, but to call dismissViewControllerAnimated:.



回答2:

try it with the NSNotificationCenter :) register an observer where the updates should be done and fire a notification where the changes are done. take a look to this tutorial for regestration and firering ;)