DEV Community

Lankinen
Lankinen

Posted on

CS193p Notes - Lecture 12: Core Data

  • Core data
    • Object-oriented database
    • Core Data uses SQL to store the data but interacting with it happens using Swift and object-oriented programming
  • The objects we create in the database are ObservableObjects
  • @FetchRequest fetches the objects and represents a "standing query"
  • To get Core Data to a project it's required to check the box when creating a new project
    • If you already have a project where you want to add Core Data, create a new project and copy paste everything there

Alt Text

AppName.xcdatamodeId

SceneDelgate.swift creates context that is then passed to all views using .environment

@Environment(\.managedObjectContext) var context
...
.sheet(isPresented: $showFilter) {
  FilterFlights(flightSearch: self.$flightSearch, isPresented: self.$showFilter)
    .environment(\.managedObjectContext, self.context)
@Environment(./managedObjectContext) var context
let flight = Flight(context: context)
flight.aircraft = "B737"
let ksjc = Airport(context: context)
ksjc.icao = "KSJC"
flight.origin = ksjc // add flight to ksjc.flightsFrom
try? context.save() // disk might be full but in general don't fail

let request = NSFetchRequest<Flight>(entityName: "Flight")
request.predicate = NSPredicate(format: "arrival < %@ and origin = %@", Date(), ksjc)
request.sortDescriptors = [NSSortDescriptor(key: "indent", ascending: true)]
let flights = try? context.fetch(request) // KSJC flights sorted by ident
// flights is nil if fetch failed, [] if no such flights, otherwise [Flight]

@RealLankinen

Originally published here

Top comments (0)