0
0
iOS Swiftmobile~5 mins

Core Data overview in iOS Swift

Choose your learning style9 modes available
Introduction

Core Data helps you save and manage app data easily on your device. It keeps your app's information safe and organized.

You want to save user notes or settings that stay after the app closes.
You need to store a list of items like contacts or tasks.
Your app needs to remember user progress or scores.
You want to organize data with relationships, like books and authors.
You want to fetch and display data quickly and efficiently.
Syntax
iOS Swift
import CoreData

// Create a data model file (.xcdatamodeld) in your project

// Use NSManagedObject subclasses to represent data entities

// Use NSPersistentContainer to set up Core Data stack
let container = NSPersistentContainer(name: "ModelName")
container.loadPersistentStores { description, error in
  if let error = error {
    fatalError("Failed to load Core Data stack: \(error)")
  }
}

// Use context to save or fetch data
let context = container.viewContext

Core Data uses a data model file to define your data structure visually.

NSPersistentContainer simplifies setting up Core Data in your app.

Examples
This class represents a Person entity with name and age fields.
iOS Swift
// Define an entity class
class Person: NSManagedObject {
  @NSManaged var name: String?
  @NSManaged var age: Int16
}
This code creates and saves a new Person object.
iOS Swift
// Save a new Person
let person = Person(context: context)
person.name = "Alice"
person.age = 30
try? context.save()
This fetches all saved Person objects from Core Data.
iOS Swift
// Fetch all Person objects
let request = NSFetchRequest<Person>(entityName: "Person")
let people = try? context.fetch(request)
Sample App

This SwiftUI app shows a list of people saved in Core Data. You can add a new person by tapping the button. The list updates automatically.

iOS Swift
import SwiftUI
import CoreData

struct ContentView: View {
  @Environment(\.managedObjectContext) private var viewContext
  @FetchRequest(entity: Person.entity(), sortDescriptors: []) private var people: FetchedResults<Person>

  var body: some View {
    VStack {
      List(people, id: \.objectID) { person in
        Text(person.name ?? "Unknown")
      }
      Button("Add Person") {
        let newPerson = Person(context: viewContext)
        newPerson.name = "New Person"
        newPerson.age = 30
        try? viewContext.save()
      }
    }
  }
}

@main
struct CoreDataApp: App {
  let container = NSPersistentContainer(name: "ModelName")

  init() {
    container.loadPersistentStores { _, error in
      if let error = error {
        fatalError("Core Data failed to load: \(error)")
      }
    }
  }

  var body: some Scene {
    WindowGroup {
      ContentView()
        .environment(\.managedObjectContext, container.viewContext)
    }
  }
}
OutputSuccess
Important Notes

Always save the context after adding or changing data to keep it stored.

Use @FetchRequest in SwiftUI to automatically update UI when data changes.

Core Data can handle complex data and relationships, but start simple.

Summary

Core Data stores and manages app data on the device.

Use NSPersistentContainer to set up Core Data easily.

Use NSManagedObject subclasses to represent your data entities.