FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

SOLVED: Tutorial for using Core Data in a "Command Line Tool" project?

Forums > macOS

Hey folks,

I would like to use Core Data in a simple Command Line Tool project I created in Xcode.

What are the steps neccessary to make it available in my project?

How to make the SQLite database be part of my build, etc.?

Would love to have a tutorial or so to lean on.

Thanks in advance, guys!

   

Hi @Bolandross. This was something I've also been wondering about for a long time but didn't know how to do. I couldn't find any tutorial either so I decided to try and figure it out.

  1. Create a new command line app, or just open one of your old ones.
  2. Click File-> and add a data model. Name it "Main"
  3. Add an Entity called 'Item' with one attribute called name of type string
  4. Now click on 'Item' in your model and find on the right side menu where it says "Codegen"
  5. Change codegen to "Manual/None"
  6. Now select your Main datamodel and click Editor->Create NSManagedObjectModel Subclass
  7. This will create two files in your project.
  8. Now lets write some code in your main.swift.
import Foundation
import CoreData

var container: NSPersistentContainer
container = NSPersistentContainer(name: "Main") // If you named your datamodel something other than main, use that instead
container.loadPersistentStores { storeDescription, error in
    if let error = error {
        fatalError("Fatal Error loading store: \(error.localizedDescription)")
    }
}

// Now lets create a new item and add it to the database.
var viewContext = container.viewContext
var newItem = Item(context: viewContext)
newItem.name = "Ralph"

do {
    try viewContext.save()
    print("Saved successfully")
} catch {
    print("Could not save")
}

print("Hello, \(newItem.name!)")

// Lets try a fetch request now.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
var fetchedItems: [Item]
do {
    fetchedItems = try viewContext.fetch(fetchRequest) as! [Item]
} catch {
    print("i am error")
    fetchedItems = []
}
print("I am \(fetchedItems[0].name!)")
print("There are \(String(fetchedItems.count)) others like me")

So every time you run this one more item will be added to your database. Also steps 4,5,6, and 7 are unneccessary the program will run fine without them.

1      

Thank you very much!

One more thing: I noticed that the automatic CodeGen works fine in the preconfigured Core Data templates, but when creating it manually, Xcode gives me a lot of warnings that the Entitiy is missing. Building and running works though!

Any ideas if there is a way to solve this?

Thanks in advance and best regards Boland

   

It's just a bug in Xcode, it happens all the time unfortunately. Sometimes clicking on the data model and clicking build will work. Other times you have to click "clean build folder" and restart xcode.

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.