Lesson 8. Persist Data in iOS

In this lesson you'll learn how to persist data in iOS.

Micro Sprint 8
Activity Type Lesson
Expected Duration 30 minutes
Topic iOS persistence
Objective Learn about iOS persistence.

1. Introduction

iOS provides developers with different ways to persist app's and user's data. In this lesson we are going to use:

  1. Core Data
  2. User Defaults

Keep in mind that Firebase counts as a way to persist data in your app, as it uses its own database implementation to cache and store your user's and application information.

2. Core Data

As seen on Apple Developer Guides

Core Data is a framework built to manage the model layer objects of your application. By using it, it automates common tasks asociated with object life cycles and graph management. In order to use it, you must import the Core Data Framework into your project:

Now, create a Data Model file by right-clicking on your project and selecting the Data Model option in the New File menu, for this example name it Model:

Now you must open the App Delegate and modify the applicationWillTerminate method. Also, add two new methods, one called persistentContainer in where you'll create the database connection, and saveContext in where you'll save the context:

Now, to add objects and entities, you can use the visual editor for the Model file we created before:

  1. Look for the file called Model.xcdatamodel
  2. Click the 'Add Entity' button
  3. Add attributes in a key-value fashion and define the value type

Now you can use the Model to create key-value base objects and store information in the phone's database.

3. User Defaults

As seen on Apple Developer Guides

User Defaults is an interface to the user's database, where developers can store key-value pairs persistently accross launches of their apps. In order to store, retrieve and remove data, follow the next steps:

  1. Store data:
UserDefaults.standard.set("Moviles", forKey: "ClassName")
UserDefaults.standard.set(2018, forKey: "ClassYear")
UserDefaults.standard.set(true, forKey: "StudentsLoveIt")
  1. Retrieve data:
UserDefaults.standard.bool(forKey: "StudentsLoveIt")
UserDefaults.standard.integer(forKey: "ClassYear")
UserDefaults.standard.string(forKey: "ClassName")
  1. Remove data:
UserDefaults.standard.removeObject(forKey: "ClassName")

Version Author Date
1.0 Juan Santiago Acevedo April 9, 2018

results matching ""

    No results matching ""