Using Swift to Seed a Core Data Database

Updated on September 23, 2015 – Swift 2.0

Designing an application’s UI can be difficult without actual data to present. Early on in the design process, data sourced from something like an array can suffice. Later on, however, our data sources become more dependent on actual data stores, such as what Core Data provides us.

During development, I’ve found that it’s often convenient to seed a Core Data database with sample data so that I can preview how it’ll look in my application. Along with that, it’s nice to start with a fresh copy of the data each time I run the app. Let’s explore how to accomplish this task in Swift!

Scenario setup

I’ve created a fictitious Core Data app called “Zootastic”, which is intended to model zoos, and the animals that each zoo cares for. (I’ll give you one guess as to what kinds of shows and activities my two year old and I have been in to lately). :]

Specifically, I have the following Entities:

  • Zoo
    • name
    • location
    • animals (relationship)
  • Animal
    • commonName
    • habitat
    • classification (relationship)
    • zoos (relationship)
  • Classification
    • scientificClassification
    • family
    • order
    • animals (relationship)

I’ve created NSManagedObject subclasses for each of my entities, to make it easier to set properties.


Once a Core Data data model is set up, we’re ready to create what I called DataHelper. It serves the purpose of seeding the data store, and logging the data store’s contents back out to the console. It violates the single-responsibility principle, but wait! Don’t lynch me!

Knowing that this class is intended to be used solely for development, I didn’t put a lot of effort into separating concerns. I opted for a “here’s where I go to do all my seeding for manual testing purposes” approach.

Here are a few snippets from the class (grab the full XCode project over at GitHub):


The primary thing to take away from the initialization routine is that instead of calling out to the AppDelegate to get an instance of the NSManagedObjectContext, I’m choosing to require it to be passed in during the initialization of DataHelper. It’s a pattern I like to practice because it allows me to do unit tests in real-world applications that use Core Data.


A few observations on the code above:

  • This function may look a bit interesting. I’ve chosen to create an array of tuples that I loop over and use to extract actual Zoo information when I call NSEntityDescription.insertNewObjectForEntityForName(). It just looked nice to me to have two chunks of code to analyze inside the function: One (the array of tuples) to see all of the zoo information I plan to insert, and another (the for-loop) to do the actual inserting into the data store. Adding more Zoos in the future would mean simply adding another tuple to the array. Convenient!
  • Since I’ve created NSManagedObject subclasses for my entities, I can cast the result of NSEntityDescription.insertNewObjectForEntityForName() to an actual Zoo, to work with the properties directly.


printAllZoos() function utilizes a standard NSFetchRequest, along with an NSSortDescriptor. Check out my cheat sheet for more examples of common Core Data operations.

Once again, having the NSManagedObject subclass in place allows me to cast the result of the fetch request to a [Zoo].


seedAnimals() is the most complicated piece of the whole scenario because it depends on entities that have been previously inserted into the data store. An Animal, which is a member of some Classification lives in some habitat at a Zoo. So in order to get a complete Animal into the data store, we need to have a Classification and one or more Zoo to assign it.

I’ve chosen to go ahead and execute fetch requests for the entities I made in previous seed___() functions. Additionally, rather than deal with NSPredicate, I just grab all Classifications and all Zoos, and use array’s filter function to get the exact Entity I want.

The last thing I’ll mention / warn against, is that I am using explicitly unwrapped optionals in this function. I’ve gone ahead and “risked it”, trusting that I’m only using this technique during development time to help me see how things will look in my UI. In other words, this isn’t code that will end up in Production. It’s simply meant to help me while I’m developing, so I’ve gone ahead and done things the quick way here.

The rest of the function follows the same patterns that have already been used in this example.


Above is a peek at what my AppDelegate.swift file’s application:didFinishLaunchingWithOptions: function looks like. Nothing fancy going on here. I’m simply initializing a DataHelper instance with the NSManagedObjectContext instance that’s created in this class, and calling the seed and print functions I defined earlier.

Starting fresh every time

I’ve found that sometimes it helps to have a freshly seeded data store every time I the app while I’m in development mode. When I’m testing the UI, I may create new entities during my manual testing, but one of the convenient things about seeding the data store is that I don’t have to. And even if I did, it’s often quite nice to start fresh each run. To do this we’ll dive into some of the boilerplate code that XCode generates for us when we choose to use Core Data when we create the project. Specifically, we’ll target the persistentStoreCoordinator closure:

I’ve highlighted the key line that I added (everything else was already in place, generated for me by XCode). Adding that line removes the sqlite database. The lines that follow add it back in a fresh state.

Wrapping up

Designing an application’s UI can be difficult without actual data to present. During development, it’s often convenient to seed a Core Data database with sample data so that we can preview how it’ll look in our application. Along with that, it’s nice to start with a fresh copy of the data each time we run the app. We explored how to accomplish this task in Swift!