in Xcode 13 — Swift 5 | Adding Core Data to Existing Project

Konuralpdemirtas
5 min readAug 15, 2022

--

If you want to add Core Data functions to a project that you didn’t select the Core Data feature when creating your project, you’ll learn to add Core Data feature to your existing project in a few steps in this article.

Let’s take a look at what Core Data is.

For Apple’s own document;

Use Core Data to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.

So here we get this, it (Core Data) offers us an offline database service on device when you don’t have an internet-based database, with it’s own functions.

We can choose the Core Data function in the options given to us when creating the project in Xcode.

If you have determined to use Core Data as a database in your project and have selected these options in the project creation screen, there is no problem at all.

So where the problems start? If you did not select these options on the project creation screen, but decided to use Core Data during the development process. But there’s no need to worry, we will learn how to solve this problem in this article.

We will follow these steps…

When your current project is open, Go File-New-Project or ⇧⌘N with your keyboard shortcut.

  • Please make sure the options you see in the photo are selected.
  • It doesn’t matter what you named the new Project anyway, we’ll delete it after we’re done.
  • Create your project.

▹ Go to the AppDelegate.swift in your temporary Core Data project.

import UIKitimport CoreData@mainclass AppDelegate: UIResponder, UIApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {// Override point for customization after application launch.return true}// MARK: UISceneSession Lifecyclefunc application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {// Called when a new scene session is being created.// Use this method to select a configuration to create the new scene with.return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)}func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {// Called when the user discards a scene session.// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.// Use this method to release any resources that were specific to the discarded scenes, as they will not return.}// MARK: - Core Data stacklazy var persistentContainer: NSPersistentCloudKitContainer = {/*The persistent container for the application. This implementationcreates and returns a container, having loaded the store for theapplication to it. This property is optional since there are legitimateerror conditions that could cause the creation of the store to fail.*/let container = NSPersistentCloudKitContainer(name: "temporaryCoreDataProject")container.loadPersistentStores(completionHandler: { (storeDescription, error) inif let error = error as NSError? {// Replace this implementation with code to handle the error appropriately.// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development./*Typical reasons for an error here include:* The parent directory does not exist, cannot be created, or disallows writing.* The persistent store is not accessible, due to permissions or data protection when the device is locked.* The device is out of space.* The store could not be migrated to the current model version.Check the error message to determine what the actual problem was.*/fatalError("Unresolved error \(error), \(error.userInfo)")}})return container}()// MARK: - Core Data Saving supportfunc saveContext () {let context = persistentContainer.viewContextif context.hasChanges {do {try context.save()} catch {// Replace this implementation with code to handle the error appropriately.// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.let nserror = error as NSErrorfatalError("Unresolved error \(nserror), \(nserror.userInfo)")}}}}

Copy all these codes and paste them into your previous project’s AppDelegate.swift file. (Remember, you need to delete all the codes in AppDelegate.swift and paste them, don’t paste under your old codes.)

Please don’t forget to add “import Core Data” in the head of your AppDelegate.swift file.

After adding the codes, you can now delete your Temporary Core Data project, we’re done with it.

▹ Open your real project. Now we need the Core Data data model file.

Go File-New- File… or just ⌘N with your keyboard shortcut.

  • If you type ‘data’ in the search bar of the new document editor, you can easily find the Data Model file.
  • Usually, developers prefers to write the project name in the Data Model name like (YourProjectName.xcdatamodeld), but of course you are free to do so, you can write whatever you want.

▹ Go back to the AppDelegate.swift file.

You need to find this line of code in your AppDelegate.swift

let container = NSPersistentCloudKitContainer(name: “YourTemporaryCoreDataProjectName”)

If you remember, we got this file from the temporary Core Data Project that we created. We need change the name the “YourTemporaryCoreDataProjectName” to “OurRealProjectName” like;

let container = NSPersistentCloudKitContainer(name: “UrunlerDataModel”)

▹ After that, open your YourProjectName.xcdatamodeld and follow these steps.

Press to Add Entity.

Give name to your Entity.

And select your entity’s attributes.

That’s All. You can use Core Data in your project as you wish.

Thanks for reading and happy coding :).

--

--