0
0
Ios-swiftHow-ToBeginner ยท 4 min read

How to Use Core Data in Swift: Simple Guide with Example

To use Core Data in Swift, set up a NSPersistentContainer to manage your data model, then create, save, and fetch NSManagedObject instances representing your data. Use the container's viewContext to perform operations and save changes to persist data locally.
๐Ÿ“

Syntax

Core Data uses a NSPersistentContainer to load your data model and manage the storage. You create or fetch NSManagedObject instances to represent your data entities. Use the container's viewContext to save or fetch data.

  • NSPersistentContainer: Loads the data model and manages the context.
  • NSManagedObject: Represents a single data record.
  • viewContext: The main context to perform data operations.
swift
let container = NSPersistentContainer(name: "ModelName")
container.loadPersistentStores { description, error in
  if let error = error {
    fatalError("Failed to load Core Data stack: \(error)")
  }
}

let context = container.viewContext

// Create a new object
let entity = NSEntityDescription.entity(forEntityName: "EntityName", in: context)!
let newObject = NSManagedObject(entity: entity, insertInto: context)
newObject.setValue("Sample", forKey: "attribute")

// Save context
try? context.save()
๐Ÿ’ป

Example

This example shows how to set up Core Data, create a new record, save it, and fetch all records from the store.

swift
import UIKit
import CoreData

class CoreDataExample {
  let container: NSPersistentContainer
  
  init() {
    container = NSPersistentContainer(name: "MyModel")
    container.loadPersistentStores { _, error in
      if let error = error {
        fatalError("Core Data stack load error: \(error)")
      }
    }
  }
  
  func addPerson(name: String) {
    let context = container.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)!
    let person = NSManagedObject(entity: entity, insertInto: context)
    person.setValue(name, forKey: "name")
    try? context.save()
  }
  
  func fetchPeople() -> [String] {
    let context = container.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
    let results = try? context.fetch(fetchRequest) ?? []
    return results?.compactMap { $0.value(forKey: "name") as? String } ?? []
  }
}

// Usage
let coreData = CoreDataExample()
coreData.addPerson(name: "Alice")
coreData.addPerson(name: "Bob")
let people = coreData.fetchPeople()
print(people)
Output
["Alice", "Bob"]
โš ๏ธ

Common Pitfalls

Common mistakes when using Core Data include:

  • Not calling save() on the context after changes, so data is not persisted.
  • Forgetting to load persistent stores before using the container.
  • Using the wrong entity name or attribute keys, causing runtime errors.
  • Performing Core Data operations on background threads without proper context setup.
swift
/* Wrong: Not saving context */
let context = container.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)!
let person = NSManagedObject(entity: entity, insertInto: context)
person.setValue("Charlie", forKey: "name")
// Missing try? context.save()

/* Right: Save context after changes */
try? context.save()
๐Ÿ“Š

Quick Reference

Remember these key steps when using Core Data in Swift:

  • Initialize NSPersistentContainer with your model name.
  • Load persistent stores before accessing the context.
  • Use viewContext for main thread operations.
  • Create or fetch NSManagedObject instances for your entities.
  • Call save() on the context to persist changes.
โœ…

Key Takeaways

Initialize NSPersistentContainer with your data model and load persistent stores before use.
Use the container's viewContext to create, fetch, and save NSManagedObject instances.
Always call save() on the context after making changes to persist data.
Use correct entity names and attribute keys to avoid runtime errors.
Perform Core Data operations on the correct thread to prevent crashes.