Locally Store/Retrive the data into NSUserDefaults

NSUserDefaults class, you can save settings and properties related to application or user data.I will be showing you how you can save and retrieve different types of data using the NSUserDefaults object. I will be showing you how you can save and retrieve different types of data using the NSUserDefaults object.
Document reference  NSUserDefaults

Implement The UpdatePrefs Method

This is where the NSUserDefaults actually get saved.In this method we perform the following tasks:

  • Get reference to the NSUserDefaults object – This is done so we can call methods on it to save our data
  • call the setObject forKey method – This allows us to save a string for a given key.The key is just a string value that we will use to look up our data.
  • calling the resignFirstResponder method on the UITextField to hide the keyboard when the button (or return) is pressed
  • Update the message text in the label to read “Application Preferences Saved” to notify the user that their preferences have been saved.

Here are the steps that are taken in this method:

  • Get a Handle to the NSUserDefaults object
  • Retrieve the saved username by calling the getObject method and passing in the key @”greeting”
  • Check if the saved username is nil – If so, display the default welcome message (Welcome guest)
  • If the username is not nil, construct a new string with it using the initWithFormat constructor.  This will allow us to append the username on to the message “Welcome”.  initWithFormat takes 1 or more args.  The first is the format of the string. In our case its @”Welcome %@!”. This is saying replace the “%@” with a string (which is the next parameter).  If you have ever written in C, this is essetially the sprintf method.
  • Once this string is build, we assign it to name.text to update the label

Following are the Retrive and Store values in NSUserDefaults.

Saving The Values into the NSUserDefaults,

Retrieving the Values into NSUserDefaults,

Saving NSDictionary Values into the NSUserDefaults,

Leave a Reply

Your email address will not be published. Required fields are marked *



*