Introduction To Persistence Storage In iOS

Persistence Storage

For any device, there is persistence storage that retains the data even after the power is shut off. Every app in your phone has a persistence space which will remain there unless until you uninstall the app. It is considered as non-volatile storage.

Why We Need it

Say, you have an app which stores the high score of the user whenever he/she crosses the high score. So, the app should remember the high score even when your app is in killed state. Or, App should preserve the high score in all states unless user uninstalls the app.

Similarly, you will have such requirements where you have to store data in local storage (or, storage like iCloud).

Persistence Storage in iOS

  1. Default System (NSUserDefault)
  2. Core Data
  3. Sandboxing & Directories (FileS System)
  4. Property List
  5. Sqlite
  6. iCloud

Here, we are going to discuss about one type of the persistence storage in iOS i.e. NSUserDefault. It is one of the easiest and most used techniques for storing the data in local storage. It is analogous to Preferences in Android.


What NSUserDefault can’t do?

Avoid using NSUserDefault for saving the data in bulk. It is recommended for storing the small chunks of data. NSUserDefault can only store the following types of data:

  1. UInt
  2. Int
  3. Float
  4. Double
  5. Bool
  6. NSData
  7. String
  8. NSNumber
  9. NSDate
  10. Array
  11. Dictionary

Demo Project

We are going to create a demo project which will store your dummy name in Persistence Storage.

Step1. Add Navigation Controller in your project. Then, add a label and button with proper constraint on the two visual objects.

Add Navigation Controller

Note: I’m assuming you know how to add constraint and navigation controller.

Step 2. Create action connection of the button and outlet connection of that text field.

Say, I have textFieldName as my text field outlet and buttonSaveData(sender: AnyObject) as button action connection.


Step 3. First, I’ll declare a reference of NSUserDefault type.

  1. <code>  
  2. //Private Instances  
  3. var defaults:NSUserDefaults?  
  5. </code>  
Then, initialize the object in viewDidLoad().
  1. <code>  
  2. defaults = NSUserDefaults.standardUserDefaults()  
  3. </code>  
By doing this, I can assure that I will get the instance of NSUserDefault on load of View Controller.

Step 4. Declare a method which will store the passed string into NSUserDefault.
  1. <code>  
  2. func saveIntoPersistanceStorage(name:String){  
  4. // Save Data  
  5. defaults!.setObject(name, forKey: KEY_NAME)  
  6. print("Save to Persistence Storage !!")  
  8. }  
  10. </code>  
Here, saveIntoPersistanceStorage is the name method which takes a single string type parameter. Then, we call a method setObject() which takes two parameters : Value and Key name.

Note: Exclamantion(!) is part of optional. For now, it is out of scope.

Alike, we will write a method which will get data from Persistence Storage by the Key name.
  1. <code>  
  2. func getDataFromPersistenceStorage(key:String){  
  4. //Get Data  
  5. defaults!.stringForKey(key)  
  6. }  
  7. </code>  
All you have to remember is two methods, setObject() and stringForKey(). One is used to save the data and other is used to retrieve data from persistence storage. Though, we have different methods, like stringForKey() for String type. We’ll discuss it further in this article.

Step 5. Now, we have to invoke these two methods on correct time.

Suppose, I want to save text field’s value on Save button and retrieve the saved value on every start of the application.

Let’s do the first part.
  1. <code>  
  2. @IBAction func buttonSaveData(sender: AnyObject) {  
  4. saveIntoPersistanceStorage(textFieldName.text!)  
  5. }  
  6. </code>  
Next, when app opens for the first time, it will try to retrieve the value from persistence.
  1. <code>  
  2. override func viewDidLoad() {  
  3. super.viewDidLoad()  
  5. defaults = NSUserDefaults.standardUserDefaults()  
  7. if let storeName = defaults!.stringForKey(KEY_NAME){  
  9. print("Save name : \(storeName)")  
  10. }   
  11. }  
  12. </code>  
So, when I successfully compile the code, it looks like this.



Click on the text field and type any dummy (say, your name). Click on the Save button (Blue). Now, it’s time to close the app and restart it again.



Up Next
    Ebook Download
    View all
    View all