[IOS] Persist Data in XCode 9 with User Defaults

Persistence

This is the continuance of an effect after it is removed. Have you ever asked yourself what happens to all the data after we close the app. If the data wasn’t persisted it is deleted. In Xcode we can use user defaults to persist data. This can be demonstrated by building a very simple app and storing the data using user defaults.

Let’s start by creating a single view app and name it Persist Data Example. Set the language to Swift and leave the three boxes unchecked. On the next page if you don’t want to share your project to Github you can leave that box unchecked.

Create a Single View App

 

Head on over to the main storyboard and go to the object library. Set the font size to 50 and change the label text to 0000. Align the view to sit horizontally in the container. Pin it 90 pixels from the top of the view, give it a width of 125 pixels and a height of 60 pixels.

Add label to main storyboard

Drag a button view onto the screen from the object library. Set the button text to “Add One“. Set the font size to 50 and the text colour to Dark Text Colour. Align it horizontally in the container. Pin it 90 pixels from the bottom of the view. Give it a width of 190 pixels and a height of 70 pixels.

Add button to view

Hide the utilities panel and the document outline then open the assistant editor. Control and drag from the label to the ViewController.swift file and create an IBOutlet. Name it “counterLabel“.

Control and drag from the button to the bottom of the ViewController.swift file and create an IBAction. Make sure the type is set to UIButton. Name it “addOneButtonPressed“.

Your code should resemble the one below.

 

Create a variable to store the initial integer value:

 

Increase the value of this counter each time the button is pressed and set the label to display the value of the counter.

 

Your code should look like the one below:

Run the app on your phone or simulator.

Add One App

 

When you close the app and run it again. You will notice that the the counter starts at zero. We can solve this problem by using user defaults. The user defaults database stores key value pairs persistently across an app.

We first need to create a constant to store our user defaults.

 

We choose standard because we want to return the shared default object. Each time the button is pressed we will store the updated item to user default.

In the viewDidLoad method:

Test and run your app. When you close the app and start it again. The counter should continue from where you left off.

Your final code should look like this:

 

Happy Koding!

~Victor

Close Menu