iOS Swift — How to implement Core Data in an existing project

Abhinay
2 min readMay 21, 2024

--

Core Data:

Core Data is an Apple framework for managing an app’s data model. Here are its key features
#1- Object Graph Management: Manages interconnected objects, handling relationships and integrity.
#2- Persistence: Stores data persistently using SQLite, XML, binary, or in-memory stores.
#3- Faulting and Lazy Loading: Loads objects into memory only when needed for better performance.
#4- Versioning and Migration: Supports data model versioning and migration.
#5- Querying: Allows querying data using NSFetchRequest with predicates.

Steps to implement the Core Data in the existing project.
Step 1 —
Add data model file in your project.
New file -> Core Data -> Data Model -> Next
Give any name for your data model file (here I gave MIEModel)

Step 2 —
Create a new Swift file, give it a name related to Core Data, like CoreDataHelper, and copy and paste the following code.
Note: Replace the string MIEModel with the name of your data model.

import Foundation
import CoreData

final class CoreDataHelper {
static let shared = CoreDataHelper()
private init() { }

// Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "MIEModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()

// Core Data saving support
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}

That’s it…

How to use -
I created a QRImageEntity with only one property named “imageData”, the data type is binary to save the image.

private func saveImage(image: UIImage) {
guard let imageData = image.jpegData(compressionQuality: 1)else {
return
}

let context = CoreDataHelper.shared.persistentContainer.viewContext
// Create a new entity object
let newImageEntity = QRImageEntity(context: context)
newImageEntity.imageData = imageData

// Save the context
do {
try context.save()
print("Image saved successfully!")
} catch {
print("Failed to save image: \(error.localizedDescription)")
}
}

Through the following line we are dealing with the newly created MIECoreDataHelper class and fetching the NSManagedObjectContext object.

let context = MIECoreDataHelper.shared.persistentContainer.viewContext

Note: In the CoreDataHelper class, you can see that I created a method named saveContext(). You can call this method as needed to save the context when the app goes into the background state or terminates for any reason. To achieve this, you can use the delegates of your AppDelegate class.

If you found this post helpful, please consider sharing it and giving it applause to help others discover it too! 👏👏

Happy Coding!🧑🏻‍💻

🧑🏻‍💻****************************See you****************************🧑🏻‍💻

--

--