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

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]

https://twitter.com/reallankinen

Lecture 1
Lecture 2
Lecture 3
Lecture 4
Lecture 5
Lecture 6
Lecture 7
Lecture 8
Lecture 9
Lecture 10
Lecture 11
Lecture 12
Lecture 13
Lecture 14

Originally published: https://www.notion.so/lankinen/Lecture-12-Core-Data-4d152115085d44368d7509600259c0cb