UITextField contents are empty after popViewContro

2019-08-31 02:16发布

问题:

In my app I'm using a navigation controller. My problem is, when I go to previous view and then back to my current view, all TextFields in this view are empty.

I don't know how to save these values (in textfields) when I navigate through the stack from navigation controller.

This is my method where I call popViewControllerAnimated:

- (IBAction)swipeBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

回答1:

In your previous view's .h file declare a property:

@property (noonatomic, retain) YOURVIEWCONTROLLER *secondVC;

then in your @implementation, synthesize the property:

@synthesize secondVC;

then replace the code, where you're presenting the view controller as modal view, with this:

if(!secondVC){
    YOURVIEWCONTROLLER *controller=[[YOURVIEWCONTROLLER alloc]init.......];
    [self setSecondVC:controller];
    [controller release];//if you ain't using arc else just set it to nil
    controller=nil;
}
[self presentModalViewController:self.secondVC animated:YES];

'YOURVIEWCONTROLLER' is the name of the second View controller's class which contains textfield. Dont't forget to release the secondVC property in -dealloc. Hope it'd help.



回答2:

When you push or pop a view controller, it is loaded or unloaded from memory, respectively. You need to save the information before popping the controller and load the information after allocating a new one and before pushing it onto the stack. You can use NSUserDefaults or basic file I/O to save and reload your information.

Saving:

  • Save data using one of the methods above.
  • Then pop the view controller.

Loading:

  • Load the data.
  • Allocate a view controller.
  • Pass the data to the view controller (using properties, singletons, etc.)
  • Push the view controller.


回答3:

You have two things to tackle here: 1. Saving the content of the text fields. 2. Restoring the content of the text fields when the view controller is pushed again.

The first one you can resolve by saving the text field values to a global object, like AppDelegate or any other global singleton.

The best way to deal with 2 is to create the initializer for the view controller with text fields. For example:

- (id)initWithOptions:(NSDictionary*)options;

Then, when you need to push the controller on the stack, you get the previously saved values from the global storage from 1, and pass them in options dictionary. Then, in viewDidLoad, you assign the values to the fields.



回答4:

Why don't you set it to a property to store it? When you want to push it to show, you can alloc it only when it is a nil member.