How to Add Core Data to an Existing Xcode 8 and Swift 3 Project

You have an existing project and you’ve decided you want to use Core Data, but didn’t check that little ‘use Core Data’ checkbox when you created the project. Fear not, we will walk through the process of adding CoreData ghetto style. It’s surprisingly simple and I’ve included pictures!

Make sure you have your existing project open (we’ll call it ‘myMainProject’ for this document) and then let’s create a new project with ⇧⌘N, select ‘Single View Application’ from the ‘iOS Application’ section, click ‘Next’.

Give this project whatever name you like, we’ll be deleting it once we’ve taken from it what we need. Before you leave this screen, though, make sure you click ‘Use Core Data’ at the bottom. Then click ‘Next’.

Now, we will take from this temporary project the code that we need. Click on ‘AppDelegate.swift’ in the files navigator (⌘1). Scrolling down to line 47 we’ll see a section marked ‘Core Data stack’. Just above that is the applicationWillTermiate() function that is “Called when the application is about to terminate. Save data if appropriate.” Below that is a section marked ‘Core Data Saving support’. We want to copy both of those sections and paste them into the ‘AppDelegate.swift’ of our main project ‘myMainProject’. At the time of this writing those sections are from line 47 to line 91.

Code : CoreData Components

That’s it for the temporary project, it’s no good to us now. You can now close and delete it. We will now work only within our main project ‘myMainProject’, so switch over to that window now.

Once those lines are in the ‘AppDelegate.swift’ file, you’ll see an error on line 46 of the same file (‘Use of undeclared type ‘NSPersistentContainer’).

To resolve this error, simply add ‘import CoreData’ at the top of the file just after the ‘import UIKit’ statement on line 9.

Next, we’ll need to change the container name to match our main project. This should be around line 56 as seen below (line 10 in the gist above).

Just highlight the string and replace it with your project’s name and save.

Next, we have to create the actual data file. So, let’s create a new file, ⌘N, scroll down to the ‘Core Data’ section and select ‘Data Model’, then continue through and name the file after your project, ‘myMainProject.xcdatamodeld’ in our case.

That’s it! You should see your data file in the file manager.

You can now select your data model and start creating Entities, Relationships, and Properties.

I’d recommend the following article for how to get started with Core Data: Beginner’s Guide to Core Data in Swift 3, by Bob The Developer

I hope this was useful, if so please share, comment, and recommend!