1. Home
  2. Explore
  3. Computer Science
  4. Core Data in Swift

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Core Data in Swift

Speaker 1Speaker 2

Core Data in Swift

12:36
0:00-12:36
  1. Anna

    Welcome to lecture 12 of Stanford CS193p, Spring 2020. Today we’re moving from the mostly functional programming we’ve been doing into a little object-oriented programming, through Core Data. The goal is to store and retrieve Swift objects in a database without having to write SQL.

  2. Michael

    That’s an important distinction: Core Data uses a relational database—SQL, behind the scenes—but our code can work with objects and their properties instead of SQL tables and rows. Xcode lets us define a map between those objects and the database structure. We focus on the Swift objects, and Core Data handles the storage machinery.

  3. Anna

    And that map describes more than objects and properties. It also describes relationships between objects, which is often the key to modeling an app’s data. Xcode generates the classes from the model, and we can use Swift extensions to add our own methods and computed properties.

  4. Michael

    So the data can become the source for the UI. Instead of keeping everything in arrays or dictionaries inside a ViewModel, we can show objects fetched from the database. Core Data lets us create objects, change their properties, connect them to other objects, save them, and fetch objects that match criteria.

  5. Anna

    There’s a particularly useful connection to SwiftUI: Core Data objects are ObservableObjects, and SwiftUI has an @FetchRequest property wrapper. A fetch request can behave like a standing query rather than a one-time lookup. When database changes affect which objects match, the fetched results—and consequently the UI—can update.

  6. Michael

    To get started, the lecture recommends selecting “Use Core Data” when creating a project. Xcode creates a blank data model and adds setup code. The AppDelegate code creates a persistent container, which holds the database store, while the SceneDelegate gets an NSManagedObjectContext from that container and places it into the SwiftUI environment.

  7. Anna

    That context is essential: think of it as the window through which code accesses the database. We use it when creating objects, fetching them, and saving changes. Views can access it through the environment, but a sheet or popover starts a separate environment, so we need to pass the context into that presentation too.

  8. Michael

    The demo applies this to an Enroute app that shows flights from FlightAware. Rather than displaying network results directly, the app will save them into Core Data and have the UI read from the database. That separates the asynchronous downloading from the UI and lets the UI show whatever is currently in storage.

  9. Anna

    The model has three entities: Airport, Airline, and Flight. An Airline has a code, full name, and short name. An Airport has an ICAO identifier, latitude and longitude, location, time zone, and name. A Flight has an identifier, aircraft, arrival and departure dates, and a filed departure date.

  10. Michael

    The model also defines relationships. A Flight has an origin Airport, a destination Airport, and an Airline. An Airport can have many flights arriving and many flights departing, and an Airline can have many flights. In the model editor, those many-valued relationships become sets of Flight objects, while the Flight’s corresponding relationship points to one Airport or Airline.

  11. Anna

    Core Data keeps the two sides of a relationship consistent. If we set a Flight’s origin to an Airport, that Airport’s flightsFrom relationship is updated too. We can make the same connection by adding the Flight to the set on the Airport side. In the generated model, those relationships are object properties, not SQL operations we write ourselves.

  12. Michael

    One detail needs care: Core Data-generated properties are optional by default. That database optionality is not the same thing as a Swift design choice about whether a value should normally be absent. A record could be incomplete, for instance, so the generated property might be nil even if the app expects an identifier to be present.

  13. Anna

    The demo uses extensions to make commonly required values easier to use. For a property that should not be nil, it renames the generated storage property with an underscore and adds a computed property that exposes a non-optional value. For the many-flight relationships, it converts the generated Objective-C NSSet into a Swift Set of Flight objects, and returns an empty set if the stored set is nil.

  14. Michael

    That kind of computed-property layer is useful syntactic sugar, but it doesn’t change how database queries work. Predicates and sort descriptors refer to the actual model fields, so if the stored field is named with an underscore, a query needs that underscore name. The computed property is for convenient Swift code, not a replacement name in the database model.

  15. Anna

    Let’s look at the core operations. To create an object, we use its generated initializer with the managed object context, then set its properties just like other variables. For example, create a Flight, set its aircraft to a value such as “B737,” create an Airport, set its ICAO, and assign that Airport as the Flight’s origin.

  16. Michael

    Once we’ve made changes, we save them with context.save(). Saving can throw—one possible reason is that the device’s storage is full—so Swift requires error handling. The demo often uses try? when it’s willing to treat a failure as nil, and also shows do-catch when it wants to print or handle a save error.

  17. Anna

    Fetching starts with an NSFetchRequest for an entity, such as Flight. A predicate describes which objects to select, and sort descriptors specify how the results should be ordered. The database can do the sorting, and a list of sort descriptors can express a primary sort and additional sorting, such as last name and then first name.

  18. Michael

    Predicates use NSPredicate. For example, a Flight predicate could ask for flights whose arrival is before the current time and whose origin is a particular Airport. Predicates support a range of matching conditions, so the lecture recommends consulting the documentation when you need more than a basic equality or comparison.

  19. Anna

    Then we call context.fetch(request). That can throw too. With try?, the result is optional: nil means the fetch failed, whereas a successful fetch with no matches is an empty array. If it succeeds and finds matches, we get an array of the requested Core Data objects.

  20. Michael

    For a single object in a SwiftUI view, we can use @ObservedObject and read its properties, such as displaying a Flight’s identifier. The lecture cautions that changing a Core Data object may not automatically trigger the observed-object update in the way we expect. In the demo, when an object is updated, the code explicitly sends objectWillChange.

  21. Anna

    For collections, @FetchRequest is the central integration. It wraps a FetchedResults collection, which can be used with ForEach and can also be converted to an Array or sorted using normal collection operations. Unlike an ordinary one-time fetch, it keeps tracking database changes that affect its results.

  22. Michael

    That means adding an object—or changing an existing object so it now matches the predicate—can update the fetched results and redraw the UI. It’s a natural fit for SwiftUI’s declarative approach: describe which data should appear, and let the view reflect what is in the database.

  23. Anna

    In the Enroute example, an Airport lookup illustrates how creation and fetching fit together. The app needs an Airport for an ICAO code, but it shouldn’t create a duplicate if that Airport is already stored. So an extension adds a withICAO function that first fetches a matching Airport from the context.

  24. Michael

    That function builds an NSFetchRequest for Airport and uses a predicate matching the stored ICAO field to the supplied code. It can also set a sort descriptor, such as sorting by location. If a matching Airport exists, the function returns it; if the fetch succeeds but finds none, it creates an Airport in the supplied context and sets its ICAO.

  25. Anna

    The rest of that Airport’s information comes asynchronously from FlightAware. When the response arrives, an update method finds the Airport again and fills in values such as latitude and longitude, then saves the context. The function may initially return an Airport that has only its ICAO, so other properties need to be handled as potentially missing until the response arrives.

  26. Michael

    After a bulk update, the demo calls objectWillChange.send() so views observing that Airport can redraw. It also sends updates to related Flights when appropriate. The relationship sets need the computed-property conversion we mentioned, because the generated Objective-C-style NSSet does not provide a strongly typed Swift Set of Flight objects.

  27. Anna

    The same patterns apply to Airline and Flight. When FlightAware returns flight information, the app looks up the Flight by its identifier; if it doesn’t exist, it creates one, and either way it updates the stored fields. FlightAware supplies airport and airline codes as strings, so the app resolves those codes to Airport and Airline objects and assigns the relationships.

  28. Michael

    The first attempt at the UI can still be based on the old FlightFetcher and its string-based data, but once FlightSearch uses Airport and Airline objects, that old approach no longer fits. The demo replaces it with a @FetchRequest for Flight objects. It filters for the selected destination and sorts the results by arrival time.

  29. Anna

    A useful refactoring is to add fetchRequest helpers in extensions for the different entities. Those helpers can supply the entity name and the usual sort descriptor—for example, Flights by arrival time, Airports by location, and Airlines by name. Then callers can create a request with a predicate without repeating the setup each time.

  30. Michael

    The Flight list can pass each fetched Flight into a row view as an @ObservedObject. Since Flight now has relationships to its Airport and Airline, the row can display information through those objects—for example, a friendly airport name—instead of looking up codes in separate collections.

  31. Anna

    But a fetch request for the destination alone won’t apply every filter selected by the user. The FilterFlights view needs collections of available Airports and Airlines, so it uses its own @FetchRequest properties with a true predicate to fetch all of each entity. Because FetchedResults stays current, newly stored airports or airlines can appear in those choices.

  32. Michael

    The pickers then work with Airport and Airline objects rather than strings. The demo makes Airport comparable so a collection can be sorted, and it uses the objects’ friendly names for display. When the user confirms a changed destination, the app starts fetching incoming flights for that destination.

  33. Anna

    There’s a common crash to watch for when presenting the filter screen: a sheet has its own environment, and a FetchRequest in that sheet needs the managed object context. The fix is to read the context from the parent view’s environment and explicitly pass it into the sheet’s environment.

  34. Michael

    Finally, the FlightSearch builds a predicate from the selected destination, plus the optional origin and airline. It assembles the predicate format and its arguments step by step, using managed objects as the arguments, then gives that predicate to the Flight fetch request. That way the standing query reflects all the chosen filters, not just the destination.

  35. Anna

    Once the data is in the database, the UI can respond immediately from stored results, even while new FlightAware requests happen asynchronously. That’s the payoff: Core Data handles persistent storage and object relationships, while @FetchRequest keeps the SwiftUI display aligned with matching database contents.

  36. Michael

    So the big picture is: model entities and relationships in Xcode, use the managed object context to create, fetch, and save, and use predicates and sort descriptors to describe the data you want. Then let SwiftUI’s FetchRequest connect those results to the interface. Core Data has more advanced capabilities, but this lecture focuses on the essentials—and shows why persistent storage can be much more powerful than UserDefaults for app data.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent