core data in swift

Here are the steps to use Core Data in Swift:

  1. Create a new Xcode project and choose the option to use Core Data.
  2. Open the .xcdatamodeld file and create a new entity with its attributes.
  3. Generate the NSManagedObject subclasses for your entities by going to Editor > Create NSManagedObject Subclass.
  4. Set up a persistent container by creating a NSPersistentContainer instance in your AppDelegate.
  5. Load the persistent store by calling the loadPersistentStores() method on the persistent container.
  6. Create a managed object context by calling the viewContext property on the persistent container.
  7. Use the managed object context to create, read, update and delete records in Core Data.

Here's an example of adding an entry to a Core Data entity:

main.swift
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
    return
}

let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
let person = NSManagedObject(entity: entity, insertInto: managedContext)

person.setValue("John", forKey: "name")

do {
    try managedContext.save()
} catch let error as NSError {
    print("Could not save. \(error), \(error.userInfo)")
}
482 chars
16 lines

gistlibby LogSnag