Saving Local Data with Core Data
Learn how to use Core Data to persist data locally on a user's device, from setting up your project to creating, and saving data entities.
Note:
This tutorial covers the basics of Apple's Core Data framework for storing data locally on the device.
Overview
To store data persistently within an application, Xcode provides the Core Data framework. It's a powerful and flexible object graph and persistence framework that allows you to manage the model layer of your application.
Reference:
Step 1: Enabling Core Data in Your Project
The easiest way to set up Core Data is to enable it when you create a new project. Simply check the "Use Core Data" box in the project setup screen.
This will automatically generate the necessary Core Data stack setup code in your AppDelegate.swift file.
Step 2: Defining Your Data Model
Core Data uses a data model file (with a .xcdatamodeld extension) to define your app's data structures. Think of this as defining the schema for your local database.
- Open the
.xcdatamodeldfile in your project. - Click "Add Entity" to create a new entity (similar to a table in a database or a collection in Firebase). For this example, we'll name it
Shopping. - With the
Shoppingentity selected, add attributes (like columns in a table). We'll addname(String),size(String), andid(UUID).
Step 3: Accessing the Core Data Context
To interact with Core Data (saving, fetching, etc.), you need access to the NSManagedObjectContext. The boilerplate code for this is in AppDelegate. Here’s how you get a reference to it from your UIViewController:
// In your UIViewController
import UIKit
import CoreData
// Get a reference to the AppDelegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// Get the managed object context
let context = appDelegate.persistentContainer.viewContext
Step 4: Creating and Saving Data
Now, let's write the code to save a new Shopping item.
1. Create a New Managed Object
First, create a new instance of your entity.
let newShoppingItem = NSEntityDescription.insertNewObject(forEntityName: "Shopping", into: context)
2. Set Attribute Values
Use the setValue(_:forKey:) method to populate the attributes of your new object.
// Assuming you have nameTextField and sizeTextField outlets
newShoppingItem.setValue(nameTextField.text!, forKey: "name")
newShoppingItem.setValue(sizeTextField.text!, forKey: "size")
newShoppingItem.setValue(UUID(), forKey: "id") // Assign a unique ID
3. Save the Context
The changes you've made so far are only in memory. To persist them to the device's storage, you must save the context. This is a "throwing" operation, so it needs to be done within a do-try-catch block.
do {
try context.save()
print("Success: Data saved!")
} catch {
print("Error saving context: \(error)")
}
Here is the complete function for saving the data:
@IBAction func saveButtonTapped(_ sender: UIButton) {
// 1. Get reference to AppDelegate and context
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext
// 2. Create a new object
let newShoppingItem = NSEntityDescription.insertNewObject(forEntityName: "Shopping", into: context)
// 3. Set its values
newShoppingItem.setValue(nameTextField.text!, forKey: "name")
newShoppingItem.setValue(sizeTextField.text!, forKey: "size")
newShoppingItem.setValue(UUID(), forKey: "id")
// 4. Save the context
do {
try context.save()
print("Successfully saved data.")
// Optionally, clear text fields or navigate away
} catch {
print("Failed to save data: \(error)")
}
}
Note:
Core Data is a powerful framework for local data persistence. This tutorial covers only the saving aspect. You'll also need to learn how to fetch, update, and delete data to fully manage your app's data lifecycle.