Welcome to this in-depth Swift tutorial on the Core Data Stack! In this lesson, we'll explore the Core Data framework that helps manage persistent data in your iOS apps. Let's dive right in!
Core Data is a high-level object-graph persistence and relationship manager included with Cocoa Touch. It helps manage complex data models, eliminating the need for manual SQL database interaction.
When to use Core Data?
First, let's import the required Core Data modules in your Swift file:
import Foundation
import CoreDataCreate a NSPersistentContainer object to manage the persistence of our data:
let container = NSPersistentContainer(name: "YourDataModelName")Now, load the data model into our container:
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}The viewContext is the main context you'll use to perform save operations:
let context = container.viewContextTo save the data, simply call the save() method on the context:
do {
try context.save()
} catch {
let error = error as NSError
fatalError("Unresolved error \(error), \(error.userInfo)")
}To fetch data, use a NSFetchRequest:
let fetchRequest: NSFetchRequest<YourEntity> = YourEntity.fetchRequest()Now, let's create a simple Todo List app to practice using Core Data. We'll have a TodoItem entity with attributes title, description, and isCompleted.
First, create a new file TodoItem+CoreDataProperties.swift and define the properties:
import Foundation
import CoreData
extension TodoItem {
@nonobjc public class func fetchRequest() -> NSFetchRequest<TodoItem> {
return NSFetchRequest<TodoItem>(entityName: "TodoItem")
}
@NSManaged public var title: String?
@NSManaged public var description: String?
@NSManaged public var isCompleted: Bool
}Now, let's create a new TodoItem and save it to the context:
let newTodoItem = TodoItem(context: context)
newTodoItem.title = "Buy groceries"
newTodoItem.description = "Milk, eggs, bread"
newTodoItem.isCompleted = false
do {
try context.save()
} catch {
let error = error as NSError
fatalError("Unresolved error \(error), \(error.userInfo)")
}Finally, let's fetch all TodoItems and display them in a table view:
let fetchRequest = TodoItem.fetchRequest()
do {
let items = try context.fetch(fetchRequest)
// Display items in a table view
} catch {
let error = error as NSError
fatalError("Unresolved error \(error), \(error.userInfo)")
}In this tutorial, we learned about Core Data, a high-level framework for managing persistent data in iOS apps. We built the Core Data stack, created a simple Todo List app, and practiced creating, saving, and fetching data.