Working with Core Data in Swift - Tutorial

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 15, 2024
Working with Core Data in Swift

Working with Core Data in Swift

Core Data is a framework provided by Apple in iOS and macOS to manage the model layer objects in your application. It allows you to persist and manage data in your application using a high-level interface. In this tutorial, we will learn how to work with Core Data in Swift.

Setting up Core Data in Swift

First, you need to add a Core Data stack to your project. You can do this by creating a new Core Data model file (`.xcdatamodeld`) in your Xcode project. Add entities, attributes, and relationships to the Core Data model as per your application's requirements.

import CoreData

class CoreDataManager {
    static let shared = CoreDataManager()
    
    private init() {}
    
    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "YourDataModel")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    
    var managedObjectContext: NSManagedObjectContext {
        return persistentContainer.viewContext
    }
}

Fetching Data from Core Data

To fetch data from Core Data, you can use `NSFetchRequest` and `NSManagedObjectContext`. You can specify predicates, sorting options, and fetch limits as per your requirements.

func fetchItems() -> [Item] {
    let fetchRequest: NSFetchRequest = Item.fetchRequest()

    do {
        let items = try CoreDataManager.shared.managedObjectContext.fetch(fetchRequest)
        return items
    } catch {
        print("Error fetching items: \(error.localizedDescription)")
        return []
    }
}

Adding Data to Core Data

To add data to Core Data, you can create a new managed object, set its attributes, and save the managed object context.

func addItem(name: String) {
    let newItem = Item(context: CoreDataManager.shared.managedObjectContext)
    newItem.name = name
    
    do {
        try CoreDataManager.shared.managedObjectContext.save()
    } catch {
        print("Error saving item: \(error.localizedDescription)")
    }
}