Ios – How to use NSUserDefaults with AppDelegate


I am trying to use NSUserdefaults to save some data from a text field, I want it to be saved when the application quits and loaded when the application starts, however I have run into a wall.

The methods that I want to use are all in the AppDelegate, Now I do not understand how to use AppDelegate very well, I have thought of two possible ways to achieve this, I have no idea if it would work though.

  1. Import AppDelegate and over ride the methods inside my VC
  2. create an instance of my VC in AppDelegate and allow AppDelegate to set and retrieve the text of my UITextField – (Don't this go against the MVC paradigm?)

Any suggestions would appreciated

Thank you very much for your time

Best Solution

Rather than keep the text field in your AppDelegate, keep the text. I'd do the following:

1) In AppDelegate.h:

@property (strong, nonatomic) NSString *textToBeSaved;

2) In AppDelegate.m, read and write textToBeSaved to NSUserDefaults when your app launches and terminates. On launch:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.textToBeSaved = [defaults objectForKey:@"save_me"];

and, before termination:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:self.textToBeSaved forKey:@"save_me"];
BOOL success = [defaults synchronize];

3) In SomeViewController.m that naturally owns the UITextField, in viewWillAppear:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
myTextField.text = appDelegate.textToBeSaved;

4) When you set the textToBeSaved depends on your UI, but whenever you know the text is ready (say on textFieldShouldReturn, or shouldEndEditing), you can hand the string to AppDelegate:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.textToBeSaved = myTextField.text;

If there's no UI to let the user accept the text, you can save the string on (textField:shouldChangeCharactersInRange:replacementString).