Introduction To Persistence Storage In iOS

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

Default System (NSUserDefault)

Core Data

Sandboxing & Directories (FileS System)

Property List

Sqlite

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:

UInt

Int

Float

Double

Bool

NSData

String

NSNumber

NSDate

Array

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.

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.

<code>

//Private Instances

var defaults:NSUserDefaults?

</code>

Then, initialize the object in viewDidLoad().

<code>

defaults = NSUserDefaults.standardUserDefaults()

</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.

<code>

func saveIntoPersistanceStorage(name:String){

// Save Data

defaults!.setObject(name, forKey: KEY_NAME)

print("Save to Persistence Storage !!")

}

</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.

<code>

func getDataFromPersistenceStorage(key:String){

//Get Data

defaults!.stringForKey(key)

}

</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.

<code>

@IBAction func buttonSaveData(sender: AnyObject) {

saveIntoPersistanceStorage(textFieldName.text!)

}

</code>

Next, when app opens for the first time, it will try to retrieve the value from persistence.

<code>

override func viewDidLoad() {

super.viewDidLoad()

defaults = NSUserDefaults.standardUserDefaults()

if let storeName = defaults!.stringForKey(KEY_NAME){

print("Save name : \(storeName)")

}

}

</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.